服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

jdbc 程序实例


   b.1 using select import java.net.url;
  import java.sql.*;
  class select {
  public static void main(string argv[]) {
  try {
  // create a url specifying an odbc data source name.
  string url = "jdbc:odbc:wombat";
  // connect to the database at that url.
  connection con = drivermanager.getconnection(url, "kgh", "");
  // execute a select statement
  statement stmt = con.createstatement();
  resultset rs = stmt.executequery("select a, b, c, d, key from table1");
  // step through the result rows.
  system.out.println("got results:");
  while (rs.next()) {
  // get the values from the current row:
  int a = rs.getint(1);
  bigdecimal b = rs.getbigdecimal(2);
  char c[] = rs.getstring(3).tochararray();
  boolean d = rs.getboolean(4);
  string key = rs.getstring(5);
  // now print out the results:
  system.out.print(" key=" + key);
  system.out.print(" a=" + a);
  system.out.print(" b=" + b);
  system.out.print(" c=");
  for (int i = 0; i < c.length; i++) {
  system.out.print(c[i]);
  }
  system.out.print(" d=" + d);
  system.out.print("/n");
  }
  stmt.close();
  con.close();
  } catch (java.lang.exception ex) {
  ex.printstacktrace();
  }
  }
  }
  
  b.2 using update // update a couple of rows in a database.
  import java.net.url;
  import java.sql.*;
  class update {
  public static void main(string argv[]) {
  try {
  // create a url specifying an odbc data source name.
  string url = "jdbc:odbc:wombat";
  // connect to the database at that url.
  connection con = drivermanager.getconnection(url, "kgh", "");
  // create a prepared statement to update the "a" field of a
  // row in the "table1" table.
  // the prepared statement takes two parameters.
  preparedstatement stmt = con.preparestatement(
  "update table1 set a = ? where key = ?");
  // first use the prepared statement to update
  // the "count" row to 34.
  stmt.setint(1, 34);
  stmt.setstring(2, "count");
  stmt.executeupdate();
  system.out.println("updated /"count/" row ok.");
  // now use the same prepared statement to update the
  // "mirror" field.
  // we rebind parameter 2, but reuse the other parameter.
  stmt.setstring(2, "mirror");
  stmt.executeupdate();
  system.out.println("updated /"mirror/" row ok.");
  stmt.close();
  con.close();
  } catch (java.lang.exception ex) {
  ex.printstacktrace();
  }
  }
  }

扫描关注微信公众号