java连接MySQL数据库

首先需要到官网下载正确的java数据库驱动,我用的版本:mysql-connector-java-5.1.47-bin.jar。在Eclipse下建项目sqlDemo,之后导入java数据库驱动,步骤:点击项目右键,找到“Build Path -> Configure Build Path... -> Libraries -> Add External JARs -> mysql-connector-java-5.1.47-bin.jar ”,最后选择“OK”确认。

 

 代码中“testdb”是数据库名, 需改成自己已创建的数据名,我的数据库登录名是“root”,没有设置登录密码,需根据自己登录名密码做相应修改。

 遇到错误提示: WARN: Establishing SSL connection without server's identity verification is not recommended. 
请在“jdbc:mysql://localhost:3306/testdb”后面加上“useSSL=false”,正确格式:jdbc:mysql://localhost:3306/testdb?useSSL=false

import java.sql.*;
/**
 * @author chen
 *
 */
public class SQLTest {

	/**
	 * @param args
	 */
	static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	static final String DB_URL = "jdbc:mysql://localhost:3306/testdb?useSSL=false";
	
	static final String USER = "root";
	static final String PASSWD= "";
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Connection conn = null;
		Statement stmt = null;
		try{
			Class.forName(JDBC_DRIVER);
			System.out.println("Connnect to database");
			
			conn = DriverManager.getConnection(DB_URL, USER, PASSWD);
			stmt = conn.createStatement();
			String sql;
			sql = "select * from employee";
			ResultSet rs = stmt.executeQuery(sql);
			   // 展开结果集数据库
            while(rs.next()){
                // 通过字段检索
               
                String firstName = rs.getString("first_name");
                String lastName = rs.getString("last_name");
                int age = rs.getInt("age");
                float income  = rs.getInt("income");
    
                // 输出数据
               
                System.out.print("\t 姓: " + firstName);
                System.out.print("\t 名: " + lastName);
                System.out.print("\tage: " + age);
                System.out.print("\t income: " + income);
                System.out.print("\n");
            }
	
			rs.close();
			stmt.close();
			conn.close();
				
		}catch(SQLException se){
			se.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(stmt != null)
					stmt.close();
			}catch(SQLException se2){
				
			}
			try{
				if(conn != null) conn.close();
			}catch(SQLException se){
				se.printStackTrace();
			}
		}
		System.out.println("GoodBye!");
		

	}


}

 

你可能感兴趣的:(SQL,Java)