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();
                }
            }
        }
    
    }
  • 相关阅读:
    python之np.tile()
    python中easydict的简单使用
    Python字典(Dictionary)update()方法
    Flutter学习之导航与数据的传输
    Flutter学习之重叠布局
    Flutter学习之重叠布局
    Flutter学习之纵向布局
    Flutter学习之纵向布局
    Flutter学习之GridView
    Flutter学习之GridView
  • 原文地址:https://www.cnblogs.com/haoxin963/p/3252465.html
Copyright © 2011-2022 走看看