数据库
连接MySQL
public class MySql {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/fzk?serverTimezone=GMT%2B8";
String name = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, name, password);
System.out.println(connection);
}
}
MySQL增删改查
增
Statement statement = connection.createStatement();//通过 Connection 得到 Statement 对象
String sql = "INSERT INTO student VALUES ('001', 'fzk', 20)";//MySQL 增 数据语句
int n = statement.executeUpdate(sql);
System.out.println(n);
改
Statement statement = connection.createStatement();//通过 Connection 得到 Statement 对象
String sql = "UPDATE student SET sage = 19 WHERE sno = '001'";//MySQL 改 数据语句
int n = statement.executeUpdate(sql);
System.out.println(n);
删
Statement statement = connection.createStatement();//通过 Connection 得到 Statement 对象
String sql = "DELETE FROM student WHERE sno = '001'";//MySQL 删 数据语句
int n = statement.executeUpdate(sql);
System.out.println(n);
查
Statement statement = connection.createStatement();//通过 Connection 得到 Statement 对象
ResultSet resultSet = statement.executeQuery("SELECT * FROM student WHERE sno = '001'");
while(resultSet.next()) {
String sno = resultSet.getString("sno");
String sname = resultSet.getString("sname");
int sage = resultSet.getInt("sage");
System.out.println(sno + ", " + sname + ", " + sage);
}
完整代码
public class MySql {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
/*
* 连接数据库
*/
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/fzk?serverTimezone=GMT%2B8";
String name = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, name, password);
/*
* 数据库增删改查
*/
Statement statement = connection.createStatement();//通过 Connection 得到 Statement 对象
String sql = "INSERT INTO student VALUES ('003', 'kkk', 20)";//MySQL 增 数据语句
String sql = "UPDATE student SET sage = 19 WHERE sno = '001'";//MySQL 改 数据语句
String sql = "DELETE FROM student WHERE sno = '001'";//MySQL 删 数据语句
int n = statement.executeUpdate(sql);
ResultSet resultSet = statement.executeQuery("SELECT * FROM student WHERE sno = '001'");
while(resultSet.next()) {
String sno = resultSet.getString("sno");
String sname = resultSet.getString("sname");
int sage = resultSet.getInt("sage");
System.out.println(sno + ", " + sname + ", " + sage);
}
}
}