JDBC缩写:Java Database Connectivity
Java中对数据库的操作都是面向接口编程的,使用JDBC时,不管底层是Mysql还是Oracle,所有的操作都是一样的。数据库连接使用的是Connection接口,这个结构是定义在JavaSE的SDK中的,而不是JavaEE的SDK中的。可以看到Connection是没有子类实现的,具体的实现是每个数据库厂商提供的。各数据库厂商提供的相关类的集合被称作Java驱动程序。要想使用这些驱动程序的,使用java.sql.DriverManager可以进行调用。
通过DriverManager.getConnection(url)来获得数据库的连接,url格式为:jdbc:subprotocol:subname
在mysql中subname是数据库的名字。
通常配置信息写在文本文件中,通过Properties来构建。
下面的例子中首先将配置信息写在jdbc.properties文件中,然后通过JDBCTest类,来对database进行读写操作。
jdbc.properties
driver=com.mysql.jdbc.Driver
#high is the database name
url=jdbc:mysql://localhost:3306/high
user=root
password=1234
JDBCTest.java
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCTest {
public static void main(String[] args) throws Exception{
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
Properties properties = new Properties();
InputStream is = JDBCTest.class.getResourceAsStream("jdbc.properties");
properties.load(is);
//该语句加载后会自动初始化,在后续使用时都会使用该默认的驱动
Class.forName(properties.getProperty("driver"));
conn = DriverManager.getConnection(properties.getProperty("url"),
properties.getProperty("user"), properties.getProperty("password"));
statement = conn.createStatement();
//INSERT, UPDATE, or DELETE 都可以使用excuteUpdate方法执行
statement.executeUpdate("insert into customers(name) values('user3')");
statement.executeUpdate("delete from customers where id=2");
statement.executeUpdate("update customers set name = 'user' where name='ABCD'");
//执行Select语句
resultSet = statement.executeQuery("select id, name from customers");
//游标最开始指向第一条数据的前面,如果有数据则移动到第一条数据,以后依次移动直到最后一条
while(resultSet.next())
{
//getXXX可以是index,也可以是数据表列的名字
System.out.print("ID:" + resultSet.getInt("id"));
System.out.print(" name:" + resultSet.getString("name") + "\n");;
}
//注意这里所有的异常都没有捕获,如果正式的代码中需要再finnaly中进行关闭。
statement.close();
conn.close();
}
}
<完>