JAVA数据库编程——JDBC(一)

来源:互联网 发布:自学英语 知乎 编辑:程序博客网 时间:2024/06/07 12:59

JDBC(Java Data Base Connectivity,Java数据库连接):是一种用于执行SQL语句的Java Api,可以为多种关系数据库提供统一访问接口。


一. JDBC编程步骤

1. Load the Driver

(1). Class.forName() ;Class.forName.newInstance();new DriverName()

(2). 实例化时自动向DriverManager注册,不需要显示调用DriverManager的registerDrive方法。

需要下载相应数据库的驱动包,添加到Java项目的build path中。

2. Connect to the DataBase

(1). DriverManager.getConnection();

interface Connection:具体的API查询API文档。

3. Execute the SQL

(1). Connection.Create Statement(); 创建SQL语句的对象,interface Statement

(2). Statement.executeQuery(); 执行select语句

(3). Statement.executeUpdate(); 执行insert,update,delete语句

4. Retrieve the result data

(1). 循环取得结果。

5. Show the result data

(1). 将数据库中的各种类型转换为JAVA中的类型。getXXX方法

6. Close

(1). 后打开的先关

close the resultset;close the statement;close the connection

二. 代码

以下代码,链接的是mysql数据库,经过测试可以运行。

mysql驱动下载地址:http://www.mysql.com/downloads/mirror.php?id=412177

异常处理:保证资源被关闭,防止资源耗尽。



以上内容JDBC编程(一)初步,后续内容会继续更新。

本人学习后整理,欢迎大家指出问题。