连接数据库
连接数据库步骤:
1. 加载驱动程序。
2. 创建Connection对象。
3. 连接数据库成功。
4. 数据库使用结束后销毁Connection对象。
5. 释放连接。
操作数据库
1. 创建Statement操作类的对象。
2. 定义SQL操作语句。
3. 通过Statement对象执行SQL语句。
<pre name="code" class="java"> try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("String url, String user, String password");
PreparedStatement ps = conn.prepareStatement("String sql");
ps.setString(int parameterIndex, String x);
ResultSet rs = ps.executeQuery();
while(rs.next()){
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
查
PreparedStatement ps = conn.prepareStatement("select * from user where user_name=? and user_pwd=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
增
PreparedStatement ps = conn.prepareStatement("insert into user(user_name,user_pwd) values(?,?)");
ps.setString(1, username);
ps.setString(2, password);
int i = ps.executeUpdate();