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();
            }
        }
    }

}
原文地址:https://www.cnblogs.com/haoxin963/p/3252465.html