mysql连接测试java脚本

JDBC.java

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBC {

    public static void main(String[] args) throws IOException {

        InputStream resourceAsStream = ClassLoader.getSystemClassLoader()
                .getResourceAsStream("config.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        String ip = properties.getProperty("ip");
        String db = properties.getProperty("db");
        String name = properties.getProperty("name");
        String password = properties.getProperty("password");

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://"+ip+":3306/"+db+"?characterEncoding=utf8&useSSL=false",name,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        String sql = "select version()";
        Statement statement = null;
        try {
            statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()){
                String version = rs.getString("version()");
                System.out.println("mysql version: "+version);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

config.properties

ip=127.0.0.1
db=aaos_platform
name=root
password=root123

connect.sh

javac JDBC.java
java -cp .:mysql-connector-java-5.1.44.jar JDBC

jar包版本:

mysql-connector-java-5.1.44.jar

猜你喜欢

转载自www.cnblogs.com/scorates/p/10482229.html
今日推荐