能够正常的查询数据库,但是不能插入数据库,编译没错,就是不能插入数据,
package mybbs;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//下一次要分包了,尽量还用工厂模式
public class PersonCheckAndInsert {
DataBaseConnection dbc;
Connection con;
String sql;
PreparedStatement pstmt;
public PersonCheckAndInsert(){
dbc=new DataBaseConnection();
con=dbc.getConnection();
}
public void insert(Person p){
sql="insert into person(name,password) value(?,?)";
try {
System.out.println(p.getName()+"
"+p.getPassword());
System.out.println("执行前1");
//pstmt=con.prepareStatement(sql); //两句之
间
pstmt=con.prepareStatement(sql);
System.out.println("执行前2");
pstmt.setString(1, p.getName());
pstmt.setString(2, p.getPassword());
System.out.println("执行前3");
pstmt.executeUpdate();
System.out.println("执行后");
pstmt.close();
} catch (SQLException e) {
System.out.println("insert数据库出错,");
}finally{
dbc.close();
//实际上关的是con,
}
}
}
/*其中那句System.out.println(p.getName()+" "+p.getPassword());都能在后台
输出正常的值,然后后台还能输出“执行前1”,然后就是输出“insert出错”,
然后其他的都不能输出,其实PersonCheckAndInsert类还有一个查询的方法public
boolean check(Person p),都能够正常执行,就是这个public void insert
(Person p)方法不能正常执行*/
//以下是数据库连接类
package mybbs ;
import java.sql.* ;
public class DataBaseConnection
{
private String DBDRIVER =
"com.mysql.jdbc.Driver" ;
private String DBURL =
"jdbc:mysql://localhost/NOte?
user=root&password=root&characterEncoding=gb2312" ;
private Connection conn = null ;
public DataBaseConnection()
{
try
{
Class.forName(DBDRIVER) ;
this.conn = DriverManager.getConnection
(DBURL) ;
}
catch (Exception e)
{
}
}
public Connection getConnection()
{
return this.conn ;
}
public void close()
{
try
{
this.conn.close() ;
}
catch (Exception e)
{
}
}
}
------解决方案--------------------} catch (SQLException e) {
System.out.println("insert数据库出错,");
}
-->
} catch (SQLException e) {
e.printStackTrace();//看什么异常
System.out.println("insert数据库出错,");
}
------解决方案--------------------sql="insert into person([name],[password]) value(?,?)";
这样试试