• Java连接数据库


    需要加入JDBC的jar包
    如有多个数据库可在IP后加"/数据库名"
    package pltools.util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    public class MysqlUtil {
    
        String url;
        String driver;
        String userName;
        String password;
        Connection connection;
    
        public MysqlUtil() {
            super();
            String[] dbInfo = null;
            try {
                dbInfo = FileUtil.read("db.txt").split("
    ");
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if (dbInfo.length > 0) {
                driver = dbInfo[0].split("=")[1];
                url = dbInfo[1].split("=")[1];
                userName = dbInfo[2].split("=")[1];
                password = dbInfo[3].split("=")[1];
            } else {
                System.err.println("error : dbInfo is empty");
            }
            String dbString = dbInfo[0] + "
    " + dbInfo[1] + "
    " + dbInfo[2] + "
    " + dbInfo[3] + "
    ";
            FileUtil.write("sqlLog.txt", "dbInfo:
    " + dbString, false);
        }
    
        public MysqlUtil(String ip) {
            super();
            if (ip.trim().length() > 0) {
                // driver = dbInfo[0].split("=")[1];
                // url = dbInfo[1].split("=")[1];
                // userName = dbInfo[2].split("=")[1];
                // password = dbInfo[3].split("=")[1];
                driver = "com.mysql.jdbc.Driver";
                url = "jdbc:mysql://" + ip + ":3306/ePMS";
                userName = "root";
                password = "Hwroot@com";
            }
            String dbString = driver + "
    " + url + "
    " + userName + "
    " + password + "
    ";
            FileUtil.write("sqlLog.txt", "dbInfo:
    " + dbString, false);
        }
    
        private Connection getConnection() {
            Connection conn = null;
            try {
                Class.forName(driver);
                conn = DriverManager.getConnection(url, userName, password);
            } catch (Exception e) {
                FileUtil.write("sqlLog.txt", new Date() + "  getConnection Error:
    " + e.toString() + "
    ");
            }
            return conn;
        }
    
        public String[] getColumn(String sqlString, int columnIndex) throws SQLException {
            String[][] result = executeQuery(sqlString);
            String[] arr = new String[result.length];
            for (int i = 0; i < result.length; i++) {
                arr[i] = result[i][columnIndex];
            }
            return arr;
        }
    
        public String[][] executeQuery(String sqlString) throws SQLException {
            ResultSet rs = null;
            Connection conn = getConnection();
            List<String[]> list = new ArrayList<String[]>();
            try {
                Statement smt = conn.createStatement();
                if (sqlString.contains("?")) {
                    String sql = sqlString.split("\?")[1];
                    rs = smt.executeQuery(sql);
                } else {
                    rs = smt.executeQuery(sqlString);
                }
    
                while (rs.next()) {
                    ResultSetMetaData rsmd = rs.getMetaData();
                    int columnCount = rsmd.getColumnCount();
                    String[] strArray = new String[columnCount];
                    for (int i = 1; i < columnCount + 1; i++) {
                        strArray[i - 1] = rs.getString(i);
                    }
                    list.add(strArray);
                }
                conn.close();
    
            } catch (Exception e) {
                FileUtil.write("sqlLog.txt", new Date() + "  executeQuery  " + sqlString + "  Error:
    " + e.toString()
                        + "
    ");
            }
            String[][] returnArray = new String[list.size()][];
            for (int i = 0; i < returnArray.length; i++) {
                returnArray[i] = (String[]) list.get(i);
            }
            return returnArray;
        }
    
        public String getSignle(String sqlString) {
            String result = null;
            Connection conn = getConnection();
            List<String> rsList = new ArrayList<String>();
    
            try {
                Statement smt = conn.createStatement();
                ResultSet rs = null;
                if (sqlString.contains("?")) {
                    String sql = sqlString.split("\?")[1];
                    rs = smt.executeQuery(sql);
                } else {
                    rs = smt.executeQuery(sqlString);
                }
                while (rs.next()) {
                    rsList.add(rs.getString(1));
                }
                conn.close();
            } catch (SQLException e) {
                FileUtil.write("sqlLog.txt", new Date() + "  getSignle  " + sqlString + "  Error:
    " + e.toString()
                        + "
    ");
            }
            if (rsList != null && rsList.size() > 0) {
                result = rsList.get(0);
            }
            return result;
        }
    }
    
    
    


    判断是否连接成功并执行一条查询
    package IV;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class DBManager {
        public static void main(String[] args) throws InstantiationException, IllegalAccessException
        {
            String url="jdbc:mysql://10.10.12.24:3306/ePMS";
            String user="system";
            String password="Hwsystem@com";
            String sql;
            String driverclass="com.mysql.jdbc.Driver";//JDBC类名
            try
            {
                //加载JDBC驱动,当这个类被加载时,类加载器会执行该类的静态代码块从而注册驱动程序的一个实例
                Class.forName(driverclass).newInstance();  
                
                //建立数据库的连接
                Connection conn=DriverManager.getConnection(url,user,password);
                if(conn != null){
                    System.out.println("连接成功:"+url);
                }
                Statement stmt=conn.createStatement();
                sql="select * from pms_device_t;";
                //stmt.execute("use information_schema;");
                int i=0;
                ResultSet rs1=stmt.executeQuery(sql);
                while (rs1.next())
                    i++;
                if(i==0){
                    System.out.println("schedule is not excit");
                }else {
                    System.out.println("Ok");
                    
                }
                ResultSet rs=stmt.executeQuery(sql);
                while (rs.next()){
                    System.out.println(rs.getString(1)+"	"+rs.getString(2));
                }
                        
            } catch (Exception e) {
                System.out.println("连接失败:"+url);
            }
            
            
        }
        
    
    }
    
    
    
     
  • 相关阅读:
    [LeetCode#260]Single Number III
    1 sql server中添加链接服务器
    1 sql server 中cursor的简介
    1 .net将xml反序列化
    1 C# 将对象序列化
    1 SQL SERVER 实现字符串分割成table的方法
    1 asp.net 中如何把用户控件应用于母版页
    1 .net中自定义事件的步骤
    .NET中跨线程访问winform控件的方法
    1 sql server 中merge的用法
  • 原文地址:https://www.cnblogs.com/cmm2016/p/5698735.html
Copyright © 2020-2023  润新知