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();
}
}
Albatron_
慕的地6079101
慕尼黑0770482
精慕门9254224