JDBC是什么?
JDBC是一组编程API,使用JDBC,java程序可以很容易的访问多种数据库(尤其是关系型数据库).下面是java.sql包中一些核心JDBC类、接口以及异常.
1. DriverManager
2. Connection
3. Statement
4. PreparedStatement
5. CallableStatement
6. ResultSet
7. SQLException
JDBC驱动是什么?
1. JDBC驱动可以将java应用程序或客户端连接SQL数据库
2. JDBC驱动是一个实现了java.sql.Driver接口的类
3. JDBC驱动将程序语言转换成特定数据库可以识别的语言
使用Class.forName()加载JDBC驱动
String className = "org.gjt.mm.mysql.Driver";
Class driverObject = Class.forName(className);
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getHSQLConnection();
Statement st = conn.createStatement();
st.executeUpdate("create table survey (id int,name varchar(30));");
st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
rs.close();
st.close();
conn.close();
}
private static Connection getHSQLConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
使用DriverManager.registerDriver()
try {
DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
}
catch (SQLException e) {
e.printStackTrace();
}
public class MainClass {
public static void main(String[] args) {
try {
String className = "oracle.jdbc.driver.OracleDriver";
Class driverObject = Class.forName(className);
System.out.println("driverObject=" + driverObject);
System.out.println("your installation of JDBC Driver OK.");
}
catch (Exception e) {
System.out.println("Failed: JDBC Driver Error: " + e.getMessage());
}
}
}
测试MySql JDBC驱动的安装
public class MainClass {
public static void main(String[] args) {
try {
String className = "org.gjt.mm.mysql.Driver";
Class driverObject = Class.forName(className);
System.out.println("driverObject=" + driverObject);
System.out.println("your installation of JDBC Driver OK.");
} catch (Exception e) {
System.out.println("Failed: JDBC Driver Error: " + e.getMessage());
}
}
}