java中使用JDBC连接数据库的步骤?
推荐于2017-11-28
Class.forname("com.mysql.jdbc.Driver");//这是连接mysql数据库的驱动
2.获取数据库连接
java.sql.Connection conn=java.sql.DriverManager.getConnection(); 3.获取表达式
java.sql.Statement stmt=conn.createStatement("jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=GBK","root","null");//三个参数分别是数据库连接的URL,用户名,密码 4.执行SQL
java.sql.ResultSet rs=stmt.executeQuery("select * from user"); 5.显示结果集里面的数据
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
System.out.pringln();
}//执行插入语句
//stmt.executeUpdate("insert into user values(1,'中文','345')");
6.释放资源
rs.close();
stmt.close();
conn.close();
注册驱动
Class.forname("com.mysql.jdbc.Driver");//这是连接mysql数据库的驱动
获取数据库连接
java.sql.Connection conn=java.sql.DriverManager.getConnection(); 3.获取表达式
java.sql.Statement stmt=conn.createStatement("jdbc:mysql://localhost/test?
useUnicode=true&characterEncoding=GBK","root","null");//三个参数分别是数据库连接的URL,
用户名,密码 4.执行SQL
java.sql.ResultSet rs=stmt.executeQuery("select * from user"); 5.显示结果集里面的数据
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
System.out.pringln();
}//执行插入语句
//stmt.executeUpdate("insert into user values(1,'中文','345')");
释放资源
rs.close();
stmt.close();
conn.close();
2013-08-25
2.java.sql.Connection conn = DriverManager.getConnection(URL(即数据库连接的ulr),USERNAME(对应数据的用户名),PASSWORD(密码));
3.String sql = "SELECT * FROM tableName WHERE id=?";
4.java.sql.PreparedStatement ptmt = conn.getPreparedStatement(sql);
5.ptmt.setInt(1,id值);
6.java.sql.ResultSet rs = ptmt.executeQuery();
7.while(rs.next){
System.out.println(rs.getString("字段名"));
}
8.conn.close();ptmt.close();rs.close();
2013-08-25