数据库jdbc
1. 配置信息
String name="root"; String psw="123456"; String URL="jdbc:mysql://localhost:3306/system?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=false";
2. 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
3. 连接数据库
Connection connection= DriverManager.getConnection(URL,name,psw);
4. 向数据库发送sql的statement 对象
Statement statement=connection.createStatement();
5. 编写sql 语句—增删改查等、
String sql="select * from `system`.tb";
6. 执行sql语句
ResultSet rs=statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
}
rs.close();
statement.close();
connection.close();
加载驱动:
提示:Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
说明:“com.mysql.cj.jdbc.Driver” 与驱动不一样
解决方案:
改写驱动driver
Class.forName("com.mysql.cj.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver");
增删改查
- 查询全部数据
其中增删改部分与上一部分实例相同,只需传递不同的SQL语句(insert,delete,update)即可实现
String sql = "select * from student";// sql语句
ResultSet rs = s.executeQuery(sql);// 执行查询语句,并把结果集返回给ResultSet
while (rs.next()) {
int id = rs.getInt("id");// 可以使用字段名
String name = rs.getString(2);// 也可以使用字段的顺序
String pwd = rs.getString(3);
System.out.printf("%d %s %s \n", id, name, pwd);
}
使用executeQuery() 执行SQL查询语句,并将查询到的信息存储在ResultSet中
2. 查询特定数据
String p = "abcdef";
int id = 10;
String sql = "select * from student where id = '" + id + "' and password = '" + p + "'";
// 执行查询语句,并把结果集返回给ResultSet
ResultSet rs = s.executeQuery(sql);
if (rs.next())
System.out.println("账号密码正确");
else
System.out.println("账号密码错误");