zoukankan      html  css  js  c++  java
  • 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();
                }
            }
        }
    
    }
  • 相关阅读:
    IOS 面试题(不断更新...)
    IOS 数字日期转化为字符串
    C#汉字生成简拼
    ObjectiveC 深浅拷贝
    数组遍历方法forEach 和 map 的区别
    COJ1174(Shining Gems)
    POJ1062(昂贵的聘礼)
    HDOJ1879(继续畅通工程)
    最短路径经典题集(转载)
    HDOJ1863(畅通工程)
  • 原文地址:https://www.cnblogs.com/haoxin963/p/3252465.html
Copyright © 2011-2022 走看看