JDBC连接数据库 模板代码
-
加载驱动:
mysql 8.0+:Class.forName(“com.mysql.cj.jdbc.Driver”);
mysql 5.0:Class.forName(“com.mysql.jdbc.Driver”); -
加载连接:conn = DriverManager.getConnection(URL, USER, PASSWORD);
mysql 8.0+: URL = “jdbc:mysql://127.0.0.1:3306/study-mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT”
mysql 5.0:jdbc:mysql://localhost:3306/db_career?autoReconnect=true&useSSL=false&characterEncoding=utf-8 -
设置sql语句:preparedStatement = conn.prepareStatement(SQL);
preparedStatement.setString(1, “test”); -
执行查询:resultSet = preparedStatement.executeQuery();
-
关闭连接:if (resultSet != null) { resultSet.close(); } conn.close();
数据库
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 数据库配置
String URL = "jdbc:mysql://127.0.0.1:3306/study-mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";
String USER = "root";
String PASSWORD = "17633908064";
// String SQL = "select * from user";
String SQL = "select * from user where userName = ?";
// 创建相关遍历
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection conn = null;
try {
// 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
// 设置sql语句
preparedStatement = conn.prepareStatement(SQL);
// 替换sql语句中的?
preparedStatement.setString(1, "test");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.print(resultSet.getString("id") + "\t");
System.out.print(resultSet.getString("userName") + "\t");
System.out.print(resultSet.getString("password") + "\t");
System.out.print(resultSet.getString("phoneNumber") + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 最后关闭连接
if (resultSet != null) {
resultSet.close();
}
conn.close();
}
}
}