ITPub博客

首页 > 数据库 > > java连接mysql,插入语句,不知道那里错了,求查出万分感谢

java连接mysql,插入语句,不知道那里错了,求查出万分感谢

作者:apnic 时间:2019-11-07 13:37:19 0 删除 编辑

package JDBCTest;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class TestOperation {

Connection con;

Statement stmt;

ResultSet rs;

//可能有问题

private String m_JDBCDrive="com.mysql.jdbc.Driver";

private String m_JDBCConnectionURL="jdbc:mysql://127.0.0.1:3306/xsxx";

private String m_userID="root";

private String m_password="1234";

public TestOperation(){

try {

Class.forName(m_JDBCDrive).newInstance();

System.out.println("装载驱动成功");

} catch (InstantiationException e) {

System.out.println("装载驱动失败");

} catch (IllegalAccessException e) {

System.out.println("装载驱动失败");

} catch (ClassNotFoundException e) {

System.out.println("装载驱动失败");

}

}

public boolean connect(){

try {

con=DriverManager.getConnection(m_JDBCConnectionURL,m_userID,m_password);

System.out.println("数据库连接正确");

} catch (SQLException e) {

System.out.println("数据库连接失败");

return false;

}

return true;

}

public ResultSet getResult(String strSQL){

try {

rs=stmt.executeQuery(strSQL);

return rs;

} catch (SQLException e) {

System.out.println("执行SQL失败");

return null;

}

}

public boolean updateSql(String strSQL){

try {

stmt.executeUpdate(strSQL);

con.commit();

return true;

} catch (SQLException e) {

System.out.println("执行SQL语句错误");

return false;

}

}

public boolean insertSql(String strSQL){

try {

stmt.executeUpdate(strSQL);

con.commit();

return true;

} catch (SQLException sqle) {

System.out.println("insertSql():执行SQL语句错误");

return false;

}

}

public void disconnect(){

try { if(con!=null){

con.close();

con=null;

}

} catch (SQLException e) {

System.out.println("关闭数据库失败");

}

}

public static void main(String[] args) {

TestOperation test=new TestOperation();

String sql1="insert into student(user,password,ID)  values('1002','admin2','admin2')";

String sql2;

ResultSet rs;

if(test.connect()){

if(test.insertSql(sql1)){

System.out.println("插入成功");

sql2="select * from student";

if(test.getResult(sql2)!=null){

rs=test.getResult(sql2);

try{

while(rs.next()){

System.out.println(rs.getInt(1));

}

}catch(SQLException e){

e.printStackTrace();

}

}

}

test.disconnect();

}

}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1282/viewspace-3160580/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    121
  • 访问量
    794