JDBC數據庫鏈接實例

package com.action;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        //1.加載jdbc驅動程序
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        //2.建立數據庫鏈接
        String url="jdbc:mysql://localhost:3306/test";
        String userName = "root";
        String password = "root";
        Connection con = null;
        Statement stat = null;
        ResultSet res = null;
        try {
            con = DriverManager.getConnection(url, userName, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        //3.建立一個statement
        try {
            stat = con.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //4.執行sql
        try {
            res = stat.executeQuery("select * from is_staff_info");
        //5.處理結果集
            while(res.next()){
                String rmp = res.getString("1");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        //關閉jdbc鏈接
        if(res != null)//關閉記錄集
        {
            try {
                res.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if(stat != null)//關閉聲明statement
        {
            try {
                stat.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(con!=null)//關閉鏈接對象Connection
        {
            try {
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
相關文章
相關標籤/搜索