JAVA连接MySql

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySqlDemo {
	static final String DB_DRIVER="com.mysql.cj.jdbc.Driver";//for mysql 8.0
    static final String DB_URL="jdbc:mysql://localhost:3308/testdb?useSSL=false&serverTimezone=UTC"; //for mysql8.0及以上
/**********************************************************************
8.0以下版本:  
  
           DB_DRIVER="com.mysql.jdbc.Driver"; 
           DB_URL="jdbc:mysql://localhost:3308/testdb";
    ***********************************************************************/
    static final String USER="root";
    static final String PWD="root";
    static final String SQL="select * from mytable";
    private static void showmsg(String s)
    {
    	System.out.println(s);
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Connection conn=null;
        Statement stmt=null;
        try {
        	Class.forName(DB_DRIVER);
        	showmsg("加载驱动完毕.");
		} catch (Exception e) {
			// TODO: handle exception
			showmsg(e.getMessage());
			return;
		}
        
        try {
			conn=DriverManager.getConnection(DB_URL, USER, PWD);
			stmt=conn.createStatement();
		    ResultSet rs=	stmt.executeQuery(SQL);
		    while(rs.next())
		    {
		    	int id=rs.getInt("ID");
		    	String name=rs.getString("Name");
		    	int age=rs.getInt("Age");
		    	String remark=rs.getString("Remark");
		    	
		    	String value=String.format("ID:%d--Name:%s--Age:%d--Remark:%s", id,name,age,remark);
		    	showmsg(value);
		    }
		    rs.close();
		    stmt.close();
		} catch (Exception e) {
			// TODO: handle exception
			showmsg(e.getMessage());
		}finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
      showmsg("goodby");   
	}

}

  

JAVA连接MySql

上一篇:ORACLE 中如何截取到时间的年月日中的年、月、日


下一篇:使用logstash读取MySQL数据传输到es,并且@timestamp字段采用MySQL中的字段时间--建议采用这个