陌上尘

JVAA学习笔记
posts - 2, comments - 1, trackbacks - 0, articles - 4

JAVA-Derby连接

Posted on 2008-06-25 22:30 陌上尘 阅读(1681) 评论(0)  编辑  收藏 所属分类: JAVA-J2EE
import java.sql.SQLException;
/**
 * 第一个 JDBC 的 HelloWorld 程序, 数据库访问 MySQL.
 * @author BeanSoft@126.com
 * @version 0.3 2007-12-12
 */
public class JDBCHelloWorld {
    public static void main(String[] args) {
        // 1. 注册驱动
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
        } catch (ClassNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       ......
       try {
           // 2. 获取数据库的连接
           conn = java.sql.DriverManager.getConnection(
                   "jdbc:derby://localhost:1527/myeclipse",
"classiccars", "classiccars");
 // 3. 获取表达式
           stmt = conn.createStatement();
                   // 执行插入数据的 SQL
           stmt.executeUpdate("insert into Student(username, password,age) values('张三', '1234', 20)");
           // 4. 执行 SQL
           rs = stmt.executeQuery("select * from Student");
           // 5. 显示结果集里面的数据
           while(rs.next()) {
               System.out.println("编号=" + rs.getInt(1));
               System.out.println("学生姓名=" +
                       rs.getString("username"));
                                      System.out.println("密码=" + rs.getString("password"));
                                      System.out.println("年龄=" + rs.getString("age"));
                                  }
           // 执行删除数据的 SQL
          // stmt.executeUpdate("delete from Student");
                              } catch (SQLException e) {
                                  e.printStackTrace();
                              } finally {
                                 // 6. 释放资源,建议放在finally语句中确保都被关闭掉了
                                 try {
                                     rs.close();
                                 } catch (SQLException e) {
                                 }
                                 try {
                                     stmt.close();
                                 } catch (SQLException e) {
                                 }
                                 try {
                                     conn.close();
                                 } catch (SQLException e) {
                                 }
                              }
                          }
                       }




只有注册用户登录后才能发表评论。


网站导航: