JDBC
- JDBC是什么
- JDBC什么时候用
- JDBC怎么用
- 实例
JDBC是什么
- . 全称:Java Database Connectivity,是用于在Java语言编程中与数据库连接的API。
- . 作用:
- 连接到数据库
- 创建SQL语句
- 在数据库中执行SQL语句
- 返回执行结果
JDBC什么时候用
怎么用JDBC
关键字:DriverManager
- 作用:用于管理数据库驱动列表,使用通信子协议将来自Java的连接请求与适当的数据库驱动程序相匹配
- 使用:DriverManager(url,username,password)
- url:地址,具有特殊写法,比如“jdbc:mysql//localhost:3306/table_name"
- username:登录数据库的用户名
- password:登录数据库的密码
关键字:Connection
- 作用:该类具有用于联系数据库的所有方法
- 使用:Connect conn=DriverManager(url,username,password);
关键字:Statement
- 作用:将SQL语句提交到数据库
- 使用:
- 创建:Statement state=conn.createStatement();
- 提交:提交分为两种方法:
- state.executeUpdate:用于增、删、改,修改成功返回收到影响的行数,修改失败则返回0
- state.executeQuery:用于查找,返回一个ResultSet类型
- …
关键字:PreparedStatement
- 作用:自动排除注入攻击;将从控制台获取的数据注入SQL语句
- 使用:
- 创建:PreparedStatement ps=conn.preparedStatement();
- 注入:根据数据类型分类注入,并输入要注入的字段在SQL语句中的位置与要注入的内容
- ps.setInt(1,int i); //在select语句的第一处条件字段注入一个int值
- ps.setString(2,String str); //在select语句的第二处条件字段注入一个字符串
- …
关键字:ResultSet
- 作用:作为迭代器,遍历state对象
- 前提:state对象成功执行用于查询的SQL语句
- 使用:
- 创建:ResultSet rs=state.executeQuery(
select语句
); - 遍历:rs.next()
- 移动指针,若指向的数据不为null,则返回true;否则,返回false
- 获取:根据数据类型分类获取,并输入要获取的字段在返回表中的位置(从1开始),如果成功返回收到影响的行数
- rs.getInt(ColumnIndex); //获取整数型
- rs.getString(ColumnIndex); //获取字符型
- …
关键字:SQLException
实例
实例1:向数据库插入一条数据
import java.sql.*;
import java.util.Scanner;
public class JDBC1 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
Connection conn=null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/cn_xien?useSSL=true&characterEncoding=utf8";
String username="root";
String password="0611";
conn=DriverManager.getConnection(url,username,password);
String update="insert into user(uid,username,password) values(6,'孙狗','111111')";
Statement state=conn.createStatement();
int i=state.executeUpdate(update);
System.out.println(i);
}catch(Exception e){
e.printStackTrace();
}finally {
try{
if(conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
实例2:将从控制台获取的数据注入SQL语句
import java.sql.*;
import java.util.Scanner;
public class JDBC2 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
Connection conn=null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/cn_xien?useSSL=true&characterEncoding=utf8";
String username="root";
String password="0611";
conn= DriverManager.getConnection(url,username,password);
System.out.println("请输入ID:");
int uid=scan.nextInt();
System.out.println("请输入密码:");
String upwd=scan.next();
String select="update user set password=? where uid=?";
PreparedStatement ps=conn.prepareStatement(select);
ps.setString(1,upwd);
ps.setInt(2,uid);
int line = ps.executeUpdate();
System.out.println(line);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}