标签:
Java数据库连接(Java Database connectivity)简称JDBC,是Java程序与数据库系统通信的标准API,它包含一组用Java语言编写的类和接口。以下以MySQL为例,介绍使用JDBC的一般步骤:
Class.forName("com.mysql.jdbc.Driver");
String mysqlURL="jdbc:mysql://host:port/dbName";
Connection conn = DriverManager.getConnection(URL,"数据库用户名","密码");
Statement stmt = conn.createStatement();
使用Connection接口的prepareStatement方法创建一个PreparedStatement对象,该对象用于传递一个或多个输入参数的SQL语句,例如:
PreparedStatement psm = conn.prepareStatement("INSERT INTO book(bookid,name) VALUES(?,?)");
psm.setString(1, "9787208061644");
psm.setString(2, "追风筝的人");
使用Connection接口的prepareCall方法创建一个CallableStatement语句对象,该对象用于调用存储过程,例如:
CallableStatement csm = conn.prepareCall("{call validate(?,?)}");
csm.setString(1, "9787208061644");
csm.setString(2, "追风筝的人");
String sql = "SELECT * FROM book";
ResultSet rd = stmt.executeQuery(sql);
String sql = "DELETE FROM book WHERE bookid="+"‘12‘"; int n = stmt.executeUpdate(sql);
String sql = "SELECT * FROM book"; ResultSet rs = stmt.executeQuery(sql); //对结果集进行迭代 while(rs.next()){ bookid = rs.getString(1); name = rs.getString(2); System.out.println(bookid+","+name); }
String dbDriver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://host:port/dbName"; Connection conn = null; Statement stmt = null; ResultSet rs = null; Class.forName(dbDriver); conn = DriverManager.getConnection(url,"数据库用户名","密码"); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM tablename"); while(rs.next()){ //读取数据操作 } //关闭连接 rs.close(); stmt.close(); conn.close();
标签:
原文地址:http://www.cnblogs.com/xiajingzero/p/4425768.html