有重复的内容所以这边做个类用于代码的优化
package com.zhongruan;
import java.sql.*;
public class DButil {
//1.加载驱动
//2.创建链接
public static Connection getconnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/zjgm?user=root&password=123456&characterEncoding=utf-8&useSSL=true");
return con;}
public static void Cloooo (ResultSet resultSet, Statement statement, Connection connection) throws SQLException
{
if (resultSet != null) {
resultSet.close();
}
statement.close();
connection.close();
}
}
1.增加数据(注意不要增加相同的)
package com.zhongruan;
import java.sql.*;
public class Test_insert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection=DButil.getconnection();
//3.写sql
String sql= "INSERT INTO stu VALUES(3,'bob',18)";
//4.得到statement对象
PreparedStatement stmt= connection.prepareStatement(sql);
//5.执行sql
stmt.executeUpdate();
//6.关闭资源
DButil.Cloooo(null,stmt,connection);
}
}
2.删除数据
package com.zhongruan;
import java.sql.*;
public class Test_delete {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection=DButil.getconnection();
//3.写sql
String sql= "delete from stu where id=2";
//4.得到statement对象
PreparedStatement stmt= connection.prepareStatement(sql);
//5.执行sql
stmt.executeUpdate();
//6.关闭资源
DButil.Cloooo(null,stmt,connection);
}
}
3.修改数据
package com.zhongruan;
import java.sql.*;
public class Test_updata {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection=DButil.getconnection();
//3.写sql
String sql= "update stu set name='liulili',age=16 where id=2;";
//4.得到statement对象
PreparedStatement stmt= connection.prepareStatement(sql);
//5.执行sql
stmt.executeUpdate();
//6.关闭资源
DButil.Cloooo(null,stmt,connection);
}
}
4.查找数据
package com.zhongruan;
import java.sql.*;
public class Test_select {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection=DButil.getconnection();
//3.写sql
String sql= "select * from stu";
//4.得到statement对象
PreparedStatement stmt= connection.prepareStatement(sql);
//5.执行sql
ResultSet resultSet=stmt.executeQuery();
//6.处理结果集
while (resultSet.next()) {
int id=resultSet.getInt(1);
String name=resultSet.getString(2);
int age=resultSet.getInt(3);
System.out.printf("id=%d,name=%s,age=%d",id,name,age);
}
//7.关闭资源
DButil.Cloooo(resultSet,stmt,connection);
}
}