数据库JDBC连接

JDBC是一套连接数据库的接口。数据库驱动都是jar包形式存在的,里面存放了各自数据库厂家的实现类,来实现JDBC接口,jar包都是各种.class文件,是各自数据库厂家用来实现JDBC接口的类。

JDBC连接六个步骤

1.注册驱动(只执行一次,告诉JAVA程序我们所要连接哪个厂家数据库)
2.获取连接(建立和数据库的Connection连接)
3.创建sql的操作对象(statement)
4.执行sql语句(executeUpdate、executeQuery)
5.处理查询结果集(Resultset)
6.释放资源(Resultset、statement、connection)

JDBC和数据库的Connection连接
这里需要提供:数据库服务端的IP地址:localhost(127.0.0.1) (这是本机,如果连接其他电脑上的数据库,需填写相应的IP地址)
数据库的端口号: 3306 (mysql专用端口号)
数据库名称 exam(根据你自己数据库中的名称填写)
编码方式 “?characterEncoding=UTF-8”
账号 “root”
密码 “***”(没有密码就填"")

 public static void main(String[] args)  throws  Exception{
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver"); //包路径
        //2.获得连接
        String url="jdbc:mysql://localhost:3306/myyog?characterEncoding=utf-8"; //字符编码设置为utf-8
        String user="root";
        String password="1234";
        Connection connection= DriverManager.getConnection(url,user,password);
        if(connection!=null)
            System.out.println("连接到数据库啦");
        else System.out.println("连接失败");
        //3.创建sql语句的执行对象
        Statement statement =connection.createStatement();
        //4.编写sql语句
        String sql="insert into depart(id,deptname) values(10,'JDBC部门')";
        int result=statement.executeUpdate(sql); //DML增删改语句都用executeupdate

        //5.处理接收结果
        if(result==1)
            System.out.println("数据库读入成功");
        else System.out.println("数据库读入失败");
        //6.释放资源,先开后关
        statement.close();
        connection.close();
    }

从键盘录入查询

首先先在工具中建表并插入数据:

CREATE TABLE userss(
 id INT PRIMARY KEY AUTO_INCREMENT,
 username VARCHAR(20) UNIQUE NOT NULL,
 PASSWORD VARCHAR(20) NOT NULL

)CHARSET=utf8;
INSERT INTO userss VALUES(NULL,'zhangsan','1234'),(NULL,'lisi','1234');
public class Query2 {
    public static void main(String[] args) throws  Exception {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入用户名");
        String name=scanner.next();
        System.out.println("请输入密码");
        String password=scanner.next();

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/myyog","root","1234");
       Statement statement= connection.createStatement();
       ResultSet resultSet=
               statement.executeQuery("select * from userss where username='"+name+"' and password='"+password+"'");
       if(resultSet.next())
           System.out.println("查询成功");
       else System.out.println("查询失败");
       //关闭接口、释放资源
       resultSet.close();
       statement.close();
       connection.close();
    }
}

sql注入!
‘abc’ OR 1=1;#
使用了mysql的关键字和语法,形成一个永真式,并把后面的关键字给注释掉。

Statement使用字符串拼接的方式,该方式存在句法复杂繁琐,容易犯错等缺点,所以Statement在实际过程中使用的非常的少。

PreparedStatement

package com.jdbc;

import java.sql.*;
import java.util.Scanner;

public class Query2 {
    public static void main(String[] args) throws  Exception {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入用户名");
        String name=scanner.next();
        System.out.println("请输入密码");
        String password=scanner.next();

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/myyog","root","1234");
        //preparestatement  预编译语句,效率高,避免注入,动态填充
        PreparedStatement preparedStatement = connection.prepareStatement("select * from userss where username=? and password=?");
       preparedStatement.setString(1,name);
       preparedStatement.setString(2,password);
       ResultSet resultSet=preparedStatement.executeQuery();

       if(resultSet.next())
           System.out.println("查询成功");
       else System.out.println("查询失败");
       //关闭接口、释放资源
       resultSet.close();
     preparedStatement.close();
       connection.close();
    }
}

Druid数据库连接池工具类:
Druid步骤:

1.导入druid的jar包和数据库连接jar包

2.定义配置文件:是properties形式的,可以叫任意名称,可以放在任意目录下,要手动加载

3.加载配置文件

4.获取数据库连接池对象:通过工厂类 DruidDataSourceFactory

package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
  private   static DataSource ds=null;
    static {
         //加载配置文件
        try {
            Properties pro=new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds= DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    //获取连接
    public  static Connection getConnection() throws Exception{
        return  ds.getConnection();
    }
    //释放资源
    public  static  void close(ResultSet rs,Statement stmt, Connection conn){
        try {
            if(rs!=null)
                rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if(stmt!=null){
                stmt.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值