JDBC理解学习与实现
java database connectivity
1 java连接数据库
JDBC(Java Database Connectivity)是Java提供的用于连接和操作关系数据库的API。JDBC使得Java程序可以与各种数据库系统(如MySQL、Oracle、SQL Server等)进行交互,从而实现数据的存储、查询、更新和删除操作。
2、jdbc连接的api
DriverManager
Connection
sql注入攻击
是指在使用statement接口的时候,sql骚操作获取全部信息;
preparedStatement预防sql攻击
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package jdbc_advance;
import org.junit.Test;
import java.sql.*;
public class Prepared_demo1 { @Test public void testQuerySingleRomAndCol() throws Exception {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu?useSSL=false&serverTimezone=UTC","root","fanTC357"); PreparedStatement preparedStatement = connection.prepareStatement("select COUNT(*) as count from t_emp"); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int count=resultSet.getInt("count"); System.out.println(count); } resultSet.close(); preparedStatement.close(); connection.close(); } }
|
3、jdbc连接流程实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package com.atguigu.base;
import java.sql.*; import java.util.Scanner;
public class jdbc_demo2 { public static void main(String[] args) throws Exception{ String url = "jdbc:mysql://localhost:3306/atguigu?useSSL=false&serverTimezone=UTC"; String user="root"; String password="******"; Connection conn=DriverManager.getConnection(url,user,password); Statement stmt=conn.createStatement();
System.out.println("请输入一个名字"); Scanner sc=new Scanner(System.in); String name=sc.nextLine();
String sql = "SELECT emp_id,emp_name,emp_salary FROM t_emp WHERE emp_name='"+name+"'"; ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) { int empId = rs.getInt("emp_id"); String empName = rs.getString("emp_name"); double empSalary = rs.getDouble("emp_Salary");
System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" ); }
rs.close(); stmt.close(); conn.close();
} }
|