JDBC连接数据库的步骤:
- 加载数据库驱动,并注册到驱动管理器。
- 构建数据库连接的URL,基本格式为:“JDBC协议+IP地址或域名+端口+数据库名称”,如mysql的数据库连接的URL为:“jdbc:mysql://localhost:3306/test”,其中test为数据库的名称。
- 通过驱动管理器获取数据库的Connection对象,该对象为JDBC封装的数据库连接对象。其获取方式如下:DriverManager.getConnection(url,username,password);
数据库连接和使用的示例代码:
package com.Connection.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestConnect {
public static void main(String[] args) {
try {
//加载数据库驱动,并将其注册到驱动管理器
Class.forName("com.mysql.jdbc.Driver");
System.out.println("成功加载到mysql驱动器");
} catch (ClassNotFoundException e) {
System.out.println("加载mysql驱动器失败");
e.printStackTrace();
}
try {
//连接数据库
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","12345");
System.out.println("成功连接到数据库");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
while(rs.next()) {
System.out.println("用户名:"+rs.getString("name")+" "+"密码:"+rs.getString("password"));
}
} catch (SQLException e) {
System.out.println("数据库连接失败");
e.printStackTrace();
}
}
}
Statement、CallableStatement和 PreparedStatement:
CallableStatement(它从 PreparedStatement 继承而来), PreparedStatement(它从 Statement 继承而来)是Statement的子接口。
Statement是用于执行静态 SQL 语句并返回它所生成结果的对象。
Statement 对象用于执行不带参数的简单 SQL 语句;
PreparedStatement 对象用于执行带或不带 IN 参数的预编译 SQL 语句;
CallableStatement 对象用于执行对数据库已存在的存储过程的调用,添加了处理 OUT 参数的方法。
其他区别:http://blog.csdn.net/u011161786/article/details/48394751
Connection conn = DriverManager.getConnection();
Statement对象执行sql语句:
Statement stmt = conn.createStatement();//创建Statement对象
stmt.executeQuery(sql);//执行sql语句
PreparedStatement对象执行sql语句:
PreparedStatement pstmt = conn.prepareStatement(sql);//创建PreparedStatement对象
pstmt.setXXX(i,X);//若sql语句中有未知参数,将第i个未知参数设置为X,其中XXX为未知参数的类型
pstmt.executeUpdate();//执行更新操作
CallableStatement对象执行sql语句(执行调用存储过程的sql语句)
CallableStatement cstmt = conn.prepareCall("{call procedure-name(arg1,arg2...)}");//调用存储过程的语法格式
cstmt.executeQuery();//执行操作