我已经提高了 2 年的 Java 知识。今天,我开始使用数据库。我有 2 个类,即 DatabaseConnection 和 UserModel.Databaseconnection 类具有连接操作,UserModel 将添加、删除、更新等方法。我没有'还没有写删除和更新代码。我只写了添加方法。但它添加到用户。我搜索了很多关于这个的想法,但我无法解决这个问题。
这是我的连接类:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
/**
*
* @author KHn
*/
public abstract class DatabaseConnection {
private Connection connect;
private static final String dbUsername="root";
private static final String dbPassword="";
private static final String dbName="virtualblog";
private static final String dbHost="jdbc:mysql://localhost:3306/";
private String driver="com.mysql.jdbc.Driver";
private Statement st;
private ResultSet rs;
/** Creates a new instance of DatabaseConnection */
public DatabaseConnection(){
try {
Class.forName(this.driver).newInstance();
setConnect((Connection)DriverManager.getConnection(dbHost+dbName,dbUsername,dbPassword));
} catch (Exception e) {
System.out.println(e);
}
}
public Connection getConnect() {
return connect;
}
public void setConnect(Connection connect) {
this.connect = connect;
}
}
此外,这是一个 UserModelClass:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.beans.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author KHn
*/
@ManagedBean
@RequestScoped
public class UserModel extends DatabaseConnection{
private PreparedStatement ps;
private Statement st;
private ResultSet ts;
Register member =new Register();
public Register getUser() {
return member;
}
public void setUser(Register member) {
this.member = member;
}
public boolean addUser(){
try{
ps=(PreparedStatement)getConnect().prepareStatement("INSERT INTO `members`(`id`, `username`, `email`, `password`, `name`, `avatar`, `blogname`) VALUES (null,?,?,'3694406','kaan','asdasd','blog adi')");
ps.setString(2, member.getUsername());
ps.setString(3, member.getEmail());
ps.executeUpdate();
}catch (Exception e) {
System.err.println("ekleme hatasi: "+e);
}
return true;
}
/** Creates a new instance of UserModel */
public UserModel() {
}
}
我哪里做错了?你能帮我一下吗?谢谢和最好的问候。