十四、JDBC复习
-
配置pom.xml文件中配置依赖
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> </dependencies>
-
编写Java类
package com.lyh.test; import java.sql.*; public class TestJdbc { public static void main(String[] args) throws Exception { String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true"; String username="root"; String password="123456"; //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.创建连接:连接数据库,代表数据了 Connection connection = DriverManager.getConnection(url, username, password); //向数据库发送Sql的对象statement:CRUD Statement statement = connection.createStatement(); //安全的PreparedStatement preparedStatement //编写sql语句 String sql="select * from users;"; //PreparedStatement preparedStatement = connection.prepareStatement(sql); //执行查询SQL,返回一个ResultSet:结果集 ResultSet resultSet = statement.executeQuery(sql); //遍历出来 while (resultSet.next()){ System.out.println("id"+ resultSet.getInt("id")); System.out.println("name"+ resultSet.getString("name")); System.out.println("password"+ resultSet.getString("password")); System.out.println("email"+ resultSet.getString("email")); System.out.println("birthday"+ resultSet.getString("birthday")); } //关闭流 resultSet.close(); statement.close(); connection.close(); } }
-
安全的编写Java类(也就是多了一个PreparedStatement)
package com.lyh.test; import java.sql.*; public class TestJdbc2 { public static void main(String[] args) throws Exception { String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true"; String username="root"; String password="123456"; //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.创建连接:连接数据库,代表数据了 Connection connection = DriverManager.getConnection(url, username, password); //向数据库发送Sql的对象statement:CRUD //安全的PreparedStatement preparedStatement //编写sql语句 String sql="insert into users values(?,?,?,?,?);"; //预编译 PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,2); preparedStatement .setString(2,"李永辉"); preparedStatement.setString(3,"12324"); preparedStatement.setString(4,"11111"); preparedStatement.setString(5,"2012-01-02"); //执行查询SQL,返回一个ResultSet:结果集 int i = preparedStatement.executeUpdate(); if (i>0){ System.out.println("添加v成功"); } //关闭流; preparedStatement.close(); connection.close(); } }
标签:JDBC,复习,mysql,resultSet,connection,preparedStatement,sql,十四,String From: https://www.cnblogs.com/lyhidea/p/16950487.html