通过JDBC访问Mysql
1.JDBC访问Mysql示例
查询语句
public class JdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 1.载入jdbc驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2.配置基本信息
String url = "jdbc:mysql://localhost:3306/workdb?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String password = "Wcj920615*";
// 3.获取数据库连接对象
Connection connection = DriverManager.getConnection(url, username, password);
// 4.创建sql对象
Statement statement = connection.createStatement();
// 5.执行查询sql
String sql = "select * from t_students";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getObject("id"));
System.out.println(resultSet.getObject("name"));
System.out.println(resultSet.getObject("gender"));
System.out.println(resultSet.getObject("grade"));
System.out.println(resultSet.getObject("score"));
System.out.println("====================================");
}
}
}
结果:

插入语句
// 6.插入语句
String sql2 = "insert into t_students (`name`, `gender`, `grade`,`score`,`student_no`) values ('小明','2','4',95,6)";
int res = statement.executeUpdate(sql2);
if (res >= 1) {
System.out.println("insert successful.");
} else {
System.out.println("error.");
}
截图:

更新语句
// 7. 更新语句
String sql3 = "update t_students set score = 100 where id = 21";
int res = statement.executeUpdate(sql3);
if (res >= 1) {
System.out.println("update successful.");
} else {
System.out.println("error.");
}
截图:

删除语句
// 8. 删除语句
String sql4 = "delete from t_students where id = 21";
int res = statement.executeUpdate(sql4);
if (res >= 1) {
System.out.println("delete successful.");
} else {
System.out.println("error.");
}
截图:

原文链接:https://www.dianjilingqu.com/759245.html