使用JDBC连接数据库
Maven导入依赖
放入dependencies中:
<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
JDBC连接步骤
public class testJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 配置信息,项目中通常写入配置文件中
String url = "jdbc:mysql://localhost:3306/smbms?useUnicode=true&useEncoding=utf-8&useSSL=true";
String userName = "root";
String passWord = "123456";
// 1. 加载驱动 8.0以后的mysql
Class.forName("com.mysql.cj.jdbc.Driver");
// 8.0之前的mysql驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 建立链接,connection就是java眼中的数据库
Connection connection = DriverManager.getConnection(url, userName, passWord);
// 3. 获取statement ,statement会引发sql注入
Statement statement = connection.createStatement();
String sql3 = "update smbms_user set userPassword=? where id = 15"; // 用一个占位符来表示需要修改的部分
// 使用preparedStatement保证安全,但是需要提前写好sql传入
PreparedStatement preparedStatement = connection.prepareStatement(sql3);
preparedStatement.setString(1,"1234"); // 设置第一个占位符为“1234”字符串类型
System.out.println(preparedStatement.executeUpdate()+"行受到影响"); //1行受到影响
// 4. 编写sql,sql是整个jdbc连接过程中唯一需要改动的部分
String sql = "select * from smbms_user";
String sql2 = "delete from smbms_user where id = 1000";
//返回受影响的行数
System.out.println(statement.executeUpdate(sql2)+"行受到影响"); // 0行受到影响 因为没有id等于1000的
// 5. 执行sql, 返回结果集
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println("id="+ resultSet.getObject("id"));
}
// 6. 关闭连接,先开的后关闭
resultSet.close();
statement.close();
connection.close();
}
}