创建一个DBUtil类
package com.zhongruan;
import java.io.Closeable;
import java.io.RandomAccessFile;
import java.sql.*;
public class DBUtil {
public static Connection getconnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/zjgm?user=root&password=123456&characterEncoding=utf-8&useSSL=true");
return connection;
}
public static void close(ResultSet resultSet, Statement statement,Connection connection) throws SQLException {
if(resultSet!=null) {
resultSet.close();
}
statement.close();
connection.close();
}
1.增加数据
package com.zhongruan;
import javax.xml.transform.Result;
import java.sql.*;
public class insert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection = DBUtil.getconnection();
String sql="insert into stu (name,age) value ('hualili',16)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
DBUtil.close(null,statement,connection);
}
2.删除数据
package com.zhongruan;
import javax.xml.transform.Result;
import java.sql.*;
public class delete{
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection = DBUtil.getconnection();
String sql="delete from stu where id=3";
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
DBUtil.close(null,statement,connection);
}
}
3.修改数据
package com.zhongruan;
import javax.xml.transform.Result;
import java.sql.*;
public class update {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection = DBUtil.getconnection();
String sql="update stu set name='hualili',age=16 where id=1";
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
DBUtil.close(null,statement,connection);
}
}
4.查看数据
package com.zhongruan;
import javax.xml.transform.Result;
import java.sql.*;
public class select {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection connection = DBUtil.getconnection();
String sql="select * from stu";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
int age = resultSet.getInt(3);
System.out.println(id + name + age);
}
DBUtil.close(resultSet,statement,connection);
}
}