什么是JDBC
我们可以将JDBC看作是一组用于用JAVA操作数据库的API,通过这个API接口,可以连接到数据库,并且使用结构化查询语言(SQL)完成对数据库的查找,更新等操作。
JDBC连接的流程:
- 加载驱动
- 建立连接
- 准备SQL语句
- 执行SQL语句
- 处理结果
- 断开连接
JDBC连接MySQL
mysql的jdbc.properties文件配置
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE
jdbc.username=root
jdbc.password=password
例子:
public static Connection lianJie() throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mysql?serverTimezone=GMT%2B8";
String user = "root";
String password = "123456";
//2.建立连接
Connection connections = DriverManager.getConnection(url, user, password);
//返回连接对象
return connections;
}
//调用它的方法如下:
public static void query(String query) throws SQLException, ClassNotFoundException {
//获取connection对象
Connection connection = DButil.lianJie();
//3.准备SQL语句
PreparedStatement pStatement = connection.prepareStatement(query);
//4.执行SQL语句
ResultSet resultSet = pStatement.executeQuery();
//检索此 ResultSet对象的列的数量,类型和属性。
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
//返回此 ResultSet对象中的列数。
int column = resultSetMetaData.getColumnCount();
System.out.println("序号" + "\t" + "姓名" + "\t" + "年龄" + "\t" + "课程");
//5.处理结果遍历要查询的数据
while (resultSet.next()) {
//遍历行数
for (int i = 1; i <= column; i++) {
System.out.print(resultSet.getObject(i) + "\t");
}
System.out.println();
}
//6.关闭连接
resultSet.close();
pStatement.close();
connection.close();
}
}
利用PreparedStatement来执行SQL插入语句,之后再将数据打印出来:
import java.sql.*;
import java.util.Scanner;
public class TestPreparedStatement {
public static void main (String[] args) throws SQLException {
Connection conn = getConnection();
String sql = "Insert into books values(?,?,?)";
//这里使用了PreparedStatement
PreparedStatement pstat = conn.prepareStatement(sql);
//从终端读取数据 并插入到表中
Scanner in = new Scanner(System.in);
while (in.hasNext()){
String parameter = in.nextLine();
if(parameter.equalsIgnoreCase("exit")){
break;
}
//分割字段
String[] parameters = parameter.trim().split(" ");
for(int i = 0;i<parameters.length;i++){
if(i==parameters.length-1) {
pstat.setDouble(i+1,Double.parseDouble(parameters[i]));
}
pstat.setString(i+1,parameters[i]);
}
if(pstat.executeUpdate()!=1){
System.out.println("插入失败");
}
}
//打印出插入的信息
sql = "select * from books";
pstat = conn.prepareStatement(sql);
boolean done = false;
ResultSet rs = pstat.executeQuery();
//在使用rs前,要先调用其next方法
while(rs.next()){
System.out.println(rs.getString("name")+" "
+ rs.getString("author")+" "
+ rs.getString("price") //会对数据类型进行字段转换
);
}
}
//该函数用于获取连接
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testjdbc?useSSL=false&serverTimezone=Hongkong";
String username = "root";
String password = "613781zs";
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
return conn;
}
}
}
JDBC连接Oracle
Oracle的jdbc.properties文件配置
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=//用户名
jdbc.password=//密码
jdbc.dialect=org.hibernate.dialect.OracleDialect
具体例子:
import oracle.jdbc.driver.OracleDriver;
import java.sql.*;
import java.util.Properties;
/**
* Created by 10412 on 2016/12/27.
* JDBC的六大步骤
* JAVA连接Oracle的三种方式
*/
public class JdbcTest
{
public static void main(String[] args) {
Connection connect = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//第一步:注册驱动
//第一种方式:类加载(常用)
//Class.forName("oracle.jdbc.OracleDriver");
//第二种方式:利用Driver对象
Driver driver = new OracleDriver();
DriverManager.deregisterDriver(driver);
//第三种方式:利用系统参数 需在idea中配置program arguments为下面的参数
//-Djdbc.drivers = oracle.jdbc.OracleDriver
//第二步:获取连接
//第一种方式:利用DriverManager(常用)
//connect = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "你的oracle数据库用户名", "用户名密码");
connect = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "scott", "tiger");
//第二种方式:直接使用Driver
// Properties pro = new Properties();
// pro.put("user", "scott");
// pro.put("password", "tiger");
// connect = driver.connect("jdbc:oracle:thin:@127.0.0.1:1521:XE", pro);
//测试connect正确与否
System.out.println(connect);
System.out.println("链接成功");
//第三步:获取执行sql语句对象
//第一种方式:statement
statement = connect.createStatement();
//第二种方式:PreStatement
//PreparedStatement preState = connect.prepareStatement("select * from student");
//第四步:执行sql语句
//第一种方式:
resultSet = statement.executeQuery("select * from student");
//第二种方式:
// preState.setInt(1, 2);//1是指sql语句中第一个?, 2是指第一个?的values值
//resultSet = preState.executeQuery(); //执行查询语句
//查询任何语句,如果有结果集,返回true,没有的话返回false,注意如果是插入一条数据的话,虽然是没有结果集,返回false,但是却能成功的插入一条数据
// boolean execute = preState.execute();
// System.out.println(execute);
//第五步:处理结果集
while (resultSet.next())
{
int id = resultSet.getInt("SNO");
String name = resultSet.getString("SNAME");
String sex = resultSet.getString("SSEX");
System.out.println(id+" "+name+" "+sex); //打印输出结果集
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//第六步:关闭资源
try {
if (resultSet!=null) resultSet.close();
if (statement!=null) statement.close();
if (connect!=null) connect.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
JDBC连接SQL Server
import java.sql.*;
public class Main {
public static void main(String []args) {
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=你的数据库名称";
String userName="sa(你的管理员名称)";
String userPwd="你的密码";
try
{
Class.forName(driverName);
Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd);
System.out.println("success!");
}
catch(Exception e)
{
e.printStackTrace();
System.out.print("fail!");
}
}
}
说明:
在SQL Server 2000 中加载驱动和URL路径的语句是:
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample";
而sql server 2005 中加载驱动和url的语句则为
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample";
各关系型数据库的默认端口号
- MySQL:3306
- Oracle:1521
- SQL Server:1433