日期:2014-05-16 浏览次数:20560 次
?
Jdbc连接的步骤:
1.注册驱动:
有三种方式:(1).DriverManager.registerDriver(new com.mysql.jdbc.Driver());
(2).System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
(3).Class.forName("com.mysql.jdbc.Driver");// 推荐方式
?
2.创建连接:
String url = "jdbc:mysql://localhost:3306/sh";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
3.创建语句:
Statement st = conn.createStatement();
4.执行语句:
ResultSet rs = st.executeQuery("select * from student");
5.处理结果集:
while (rs.next()) {
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) );
}
6.释放资源:
rs.close();
st.close();
conn.close();
?
?
?
源代码:
?
package com.lzw;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Base {
public static void main(String[] args) throws Exception {
test();
}
static void test() throws SQLException, ClassNotFoundException {
// 1.注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver