JDBC是Sun公司提出的JavaAPI中的一部分,其含义是使用java语言来访问数据库,是java程序访问数据库的标准接口。尽管所有的数据库都支持SQL作为数据库的访问语言,但是不同的数据库引擎执行SQL语句的API有所差别,为了使编写的代码可以通用,javaAPI提供了JDBC API,使用JDBC中提供的接口和类可以在任何关系数据库中以相同的方式执行SQL语句。
JDBC访问数据库的过程
下面以MySQL数据库为例,使用JDBC实现数据库的连接
1、加载MySQL数据库连接驱动程序,改驱动程序在MySQL官网上下载。加载数据库驱动程序使用的方法时Class.forName(),该方法会将指定的类加载到JVM中。
Class.forName(“com.mysql.jdbc.Driver”);
2、设置数据库的用户名,密码,URL,不同数据库的URL会有所不同,但是基本格式为“JDBC协议+数据库的IP地址+数据库的端口号+数据库名称”。
String user=”root”;
String pwd=”123456”;
String url=”jdbc:mysql://localhost:3306/db_database01”;
3、通过JDBC API的DriverManager类的getConnection()方法来创建数据库之间的连接,该方法有三个参数,url,user,pwd。
Connection connection=DriverManager.getConnection(url,user,pwd);
4、建立连接之后,使用该连接对象创建用户操作SQL语句的Statement对象。创建Statement对象用的createStatement()方法
Statement stmt=connection.createStatement();
也可以用Connection对象创建PreparedStatement对象来执行SQL语句,使用的是PrepareStatement()方法。
PreparedStatement pstmt=connection.prepareStatement(sql);
5、调用Statement对象的execute()方法,编译执行sql语句。
String sql=”update from tb_user set age=30 where userid=1”;
stmt.execute(sql);
6、关闭数据库连接,数据库用完之后要及时关闭与数据库之间的连接,释放系统资源。
connection.close();
package sqlprogress;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBCon {
private static Connection conn=null;
public static Connection getConn()
{
try {
Class.forName("com.mysql.jdbc.Driver");
String user="root";
String pwd="123456";
String url="jdbc:mysql://localhost:3306/db_database16";
conn=DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return conn;
}
}
package sqlprogress;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class Mainprogress {
public static void main(String[] args) {
Connection connection = null;
try {
connection = DBCon.getConn();
String sql = "select name from tb_employee where id=1";
Statement stmt=connection.createStatement();
boolean a=stmt.execute(sql);
//PreparedStatement stmt = connection.prepareStatement(sql);
//boolean a=stmt.execute();
System.out.println(a);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
}
}