JDBC

大憨熊 提交于 2020-03-18 17:09:51

JDBC

  • 加载驱动
  • 获得链接的url,如果报一下错误在数据库url后加上serverTimezone=UTC

    Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

  • 获得connection链接
  • 创建Statement or PreparedStatement
    • 增、删、改使用executeUpdate
    • 查使用executeQuery
package com.claudxyz.db;

import java.sql.*;

public class ConnectJDBC {

    public static void main(String[] args) {
        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 获得链接的url
            String url = "jdbc:mysql://localhost:3306/claudxyz?serverTimezone=UTC";//
            // 数据库用户名
            String userName = "root";
            // 数据库密码
            String password = "root123";
            // 获得connection链接
            Connection connection = DriverManager.getConnection(url,userName,password);

//            String sql = "insert into t_user(id,name,password) values('4','4','4')";
            String sql = "select * from t_user where id = ? ";
            //创建Statement or PreparedStatement
//            Statement statement = connection.createStatement();

            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            // 问号为占位符
            preparedStatement.setString(1,"1");

//            int i = statement.executeUpdate(sql);

            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()){
                System.out.println("id:" + resultSet.getString(1) + " name:" + resultSet.getString("name")+ " password:" + resultSet.getString(3));
            }

//            System.out.println(i);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Statement/PreparedStatement区别

  • 创建不同
// 创建Statement
String sql = "select * from t_user where id = '1' ";
            
Statement statement = connection.createStatement();
            
ResultSet result = statement.executeQuery(sql);

// 创建PreparedStatement
String sql = "select * from t_user where id = ? ";
           
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 问号为占位符
preparedStatement.setString(1,"1");

ResultSet resultSet = preparedStatement.executeQuery();
  • 功能不同

    Statement存在sql注入的风险,即传递的参数可以拼1=1这样的语句绕开权限
    PreparedStatement使用【?】占位符的方式,不存在sql注入

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!