数据库驱动
- 应用程序通过驱动访问和操作数据库
- JDBC 提供的API可以让JAVA通过API方式访问关系型数据库,执行SQL语句,获取数据
JDBC简介
- JDBC:Java DataBase Connectivity,即java数据库连接
- 从根本来讲,JDBC是一种规范,它提供的接口,是一套完整的、可移植的访问底层数据库的程序
JDBC程序
CREATE TABLE `jdbc_users`(
`id`int(11) not null auto_increment COMMENT'唯一的标识',
`name`VARCHAR(11) not NULL,
`psw`VARCHAR(60),
`email`VARCHAR(60),
`birthday`date,
PRIMARY KEY(`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT into `jdbc_users`(name,psw,email,birthday)VALUES
('A','123456','[email protected]','1990-10-01')
INSERT into `jdbc_users`(name,psw,email,birthday)VALUES
('B','123456','[email protected]','1990-11-01'),('C','123456','[email protected]','1990-01-01')
package www.bh.c.jdbctest;
import java.sql.*;
public class Test01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.用户信息和url
String url="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username="root";
String password="123456";
//3.连接成功,数据库对象
Connection connection = DriverManager.getConnection(url, username, password);
//4.执行SQL的对象
Statement statement = connection.createStatement();
//5.使用执行SQL的对象执行SQL,可能存在结果,查看返回结果
String sql="select *from jdbc_users";
ResultSet resultSet = statement.executeQuery(sql);//返回的结果集,结果集中封装了查询出来全部的结果
while (resultSet.next()){
System.out.println("id"+resultSet.getObject("id"));
System.out.println("name"+resultSet.getObject("name"));
System.out.println("+++++++++++++++++++++++");
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}
-
步骤总结:
1.加载驱动
2.连接数据库 DriverManager
3.获得执行sql的对象 Statement
4.获得返回的结果集
5.释放连接
-
说明
//DriverManager
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
//connection 代表数据库
//数据库设置自动提交
//事务提交
//事务滚回
connection.setAutoCommit();
connection.commit();
connection.rollback();
//URL
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true";
//mysql --3306
//协议://主机地址:端口号/数据库名?参数1&参数2&参数3
//oracle端口号1521
//jdbc:oracle:thin:@localhost:1521:sid
//Statement(PrapareStatement):执行SQL的对象
String sql="select *from jdbc_users";//编写SQL语句
statement.executeQuery();//查询操作返回 ResultSet
statement.execute();//执行任何SQL
statement.executeUpdate();//更新、插入、删除,返回一个受影响的行数
//ResultSet查询的结果集:封装了所有的查询结果
//获得指定的数据类型
resultSet.getObject();//在不知道列类型的情况下使用
//知道列的类型时就使用指定的类型
resultSet.getString();
resultSet.getInt();
resultSet.getBytes();
resultSet.getByte();
resultSet.getTime();
......
//遍历,指针的移动
resultSet.beforeFirst();//移动到最前面
resultSet.afterLast();//移动到最后面
resultSet.next();//移动到下一个数据
resultSet.previous();//移动到前一行
resultSet.absolute(row);//移动到指定行
//释放资源
resultSet.close();
statement.close();
connection.close();