JDBC基本操作代码
//加载驱动
Class.forName("com.mysql.jdbc.Driver").newInstance();
//建立连接
String url="jdbc:mysql://localhost:3306/testDB?user=root&password=root&useUnicode=true&characterEncoding=gb2312";
Connection conn=DriverManager.getConnection(url);
//建立Statement对象 ,为执行sql做准备
//PreparedStatement ps = conn.prepareStatement(sql);对sql进行预编译,适合对数据库批量处理
Statement stmt=conn.createStatement();
//执行SQL查询
String sql="select * from users";
ResultSet rs=stmt.executeQuery(sql);
//建立PreparedStatement对象
String sql="select * from user where userName=? and password=?";
PreparedStatement pstmt=Conn.prepareStatement(sql);
pstmt.setString(1,"admin");
pstmt.setString(2,"liubin");
//执行动态SQL查询
ResultSet rs=pstmt.executeQuery();
//执行insert update delete等语句,先定义sql
while(rs.next)
{
out.println("你的第一个字段内容为:"+rs.getString("Name"));
out.println("你的第二个字段内容为:"+rs.getString(2));
}
rs.close();
stmt.clost();
pstmt.close();
con.close();