第一步:添加相应的驱动程序
1.准备驱动程序(拷贝项目中lib(自己创建的)中)
2.添加到项目中,右键 build Path --> add to Build Path
第二步:加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
第三步:获取连接
conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/csdn", "root", "root");
第四步:定义sql语句
例如:
String sql = "insert into user(name,pass,birth) values
('yanmei','csdn','2013-10-02')";
第五步:获取stmt对象
stmt = conn.createStatement();
第六步:执行sql语句
1.insert update delete
int i = stmt.executeUpdate(sql);
2.select
rs = stmt.executeQuery(sql);
第七步:判断处理
1.insert update delete
if(i>0)
2.select
if(rs.next())或者while(rs.next())
第八步:释放资源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-
generated catch block
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-
generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-
generated catch block
e.printStackTrace();
}
}