首先在导入jdbc驱动包之后,创建数据库并编写数据库连接代码
package jdbc_test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.Driver; public class jdbcTest { public static void main(String[] args) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub // 数据库的连接 Connection connection = null; // 预编译的Statement,使用预编译的Statement提高数据库的性能 // 通过预编译的Statement向数据库发生sql语句,数据库要对sql语句进行编译,编译完之后数据库会对得到的结果集存到数据库端的缓存中 // 下一次再发送相同的sql语句,数据库则不用重新编译,直接从缓存中拿来结果集即可,所以提高了数据库的性能。 PreparedStatement preparedStatement = null; // 结果集 ResultSet resultSet = null; try { // 加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); // 通过驱动管理类获取数据库连接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis_learning?useSSL=false", "root", "7458"); // 定义sql语句,其中?表示占位符 String sqlString = "select * from user where username = ?"; // 获取预处理statement preparedStatement = connection.prepareStatement(sqlString); // 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值 preparedStatement.setString(1, "王五"); // 向数据库发出sql执行查询,查询出结果集 resultSet = preparedStatement.executeQuery(); // 遍历查询结果集 while (resultSet.next()) { System.out.println(resultSet.getString("id") + " " + resultSet.getString("username")); } } finally { // TODO: handle finally clause // 释放资源(倒着释放) if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } } } } }
原文:https://www.cnblogs.com/yunkaiL/p/11393243.html