目录
一种Java与数据库连接的技术
Java和数据库并不是直接连接,而是通过mysql提供的jar包进行连接

关于jar包的下载以及配置详情配置见 :JDBC在idea上的配置

什么是结果集?
可以理解为数据库和程序之间交流的通道

列名是从第一列开始
- package MYSQLStudy;
-
- import java.sql.*;
-
- public class Demo1 {
- static Statement statement;
- static ResultSet resultSet;
- static Connection connection;
- public static void main(String[] args) throws SQLException {
-
- try {
- Class.forName(("com.mysql.cj.jdbc.Driver"));
- String url="jdbc:mysql://127.0.0.1:3306/text1?serverTimezone=GMT";
- String username = "root";
- String password = "QAZWSX564368";
- connection=DriverManager.getConnection(url,username,password);
- if(connection!=null){
- System.out.print("连接成功");
- }
- statement=connection.createStatement();//创建statement对象
- resultSet= statement.executeQuery("select* from student");
- while (resultSet.next()){
- int id=resultSet.getInt("sno");
- String name=resultSet.getString(2);
- Date bdate=resultSet.getDate("bdate");
- System.out.println(id);
- System.out.println(name);
- System.out.println(bdate);
- }
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }finally {
- if (resultSet!=null) resultSet.close();
- if (statement!=null) statement.close();
- if (connection!=null) connection.close();
- }
-
-
- }
- }


Class.forName(("com.mysql.cj.jdbc.Driver"));//有些教程里面没有cj
- String url="jdbc:mysql://127.0.0.1:3306/text1?serverTimezone=GMT";//数据库url
- String username = "root";//数据库账号
- String password = "QAZWSX564368";//数据库密码
- Connection connection=DriverManager.getConnection(url,username,password);
1、未导入驱动包

2、URL写错了

3、账号密码错误

4、驱动包版本不兼容


- package MYSQLStudy;
-
- import java.sql.*;
-
- public class Demo2 {
- static Statement statement;
- static ResultSet resultSet;
- static Connection connection;
-
- public static void main(String[] args) {
- try {
- Class.forName(("com.mysql.cj.jdbc.Driver"));
- String url="jdbc:mysql://127.0.0.1:3306/text1?serverTimezone=GMT";
- String username = "root";
- String password = "QAZWSX564368";
- connection= DriverManager.getConnection(url,username,password);
-
- String sql="select* from student where sname=?";
- PreparedStatement preparedStatement=connection.prepareStatement(sql);
- preparedStatement.setString(1,"小明");
- resultSet=preparedStatement.executeQuery();
- if (resultSet.next()){
- System.out.println(resultSet.getInt(1)+resultSet.getString(2)+resultSet.getString(3)+resultSet.getString(4));
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- }
- }
- }

- String sql="select* from student where sname=? and sex=?";
- PreparedStatement preparedStatement=connection.prepareStatement(sql);
- preparedStatement.setString(1,"小明");
如果引用两个通配符,却只是用了一个,就会报错