JDBC 连接mySQL(原创)

package com.sidi.oa.vo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* JDBC 连接mySQL
* 作者:朱志杰
* Apr 19, 2009 1:36:38 PM
*
*/
public class MySQLJdbc {
public String driverName = "com.mysql.jdbc.Driver";
public String url = "jdbc:mysql://localhost:3306/oa";
public String userName = "root";
public String userPwd = "me";

/**
* Apr 19, 2009 12:49:55 PM
*
* @param args
*/
public static void main(String[] args) {
   MySQLJdbc my=new MySQLJdbc();
   my.read();
}

public void read() {
   String queryString = "select userName,realName from user";
   Connection conn = null;
   Statement st = null;
   ResultSet rs = null;
   try {
    //加载驱动
    Class.forName(driverName);
    //创建连接
    conn = DriverManager.getConnection(url, userName, userPwd);
    //创建Statement
    st = conn.createStatement();
    //执行sql语句,得到查询结果
    rs = st.executeQuery(queryString);
    //输出查询结果
    while (rs.next()) {
     System.out.println("userName:" + rs.getString("userName")
       + "   realName:" + rs.getString("realName"));
    }
    // 关闭资源
    rs.close();
    st.close();
    conn.close();

   } catch (Exception ex) {
    // 输出错误信息
    ex.printStackTrace();
   } finally {
    // finally子句总是会执行(就算发生错误),这样可以保证资源的绝对关闭
    try {
     if (rs != null)
      rs.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
    try {
     if (st != null)
      st.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
    try {
     if (conn != null)
      conn.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }

   }
}

}

posted @ 2010-01-28 16:32  沙琪玛  阅读(225)  评论(0编辑  收藏  举报