1. 程式人生 > >java連結mysql資料庫-jdbc

java連結mysql資料庫-jdbc

1、工具準備

常用的java環境,即eclipse,jdk等

mysql 5.6 資料庫

當網上下載一個MySQL連線驅動:mysql-connector-java-5.1.27.jar

地址為:https://dev.mysql.com/downloads/connector/j/

2、下載後,包為zip壓縮包,解壓到任意位置,新建個java工程


3、右鍵點選javasql,選擇build path,再選擇add external Archives,將驅動包匯入進來


4、隨機建立個數據表,我這裡用的是公司的測試庫

username  root

password  test123

ip 10.1.60.23

port 3306

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

public class sqldemo {
	public String getusername()
	{
		Connection con;
		String driver="com.mysql.jdbc.Driver";
		String url="jdbc:mysql://10.1.60.62:3306/s61";
		String username="root";
		String password="test123";
		String loginname=null;
		try{
			Class.forName(driver);
			con=DriverManager.getConnection(url,username,password);
			if (!con.isClosed())
				System.out.println("Succeed conect database");
			Statement statement=con.createStatement();
			//String sql="select * from s61.t6110 where f01 in (select user_id from s61.t_user_capital_account where status="+"'YWC')";
			//System.out.println(sql);
			String sql="select * from s61.t6110 where f01=293418 ";
			//String sql="select f02 from s61.t6110 where f01 in (select f02 from s61.t6101 where f03="+"'WLZH'"+ "and f06>100000 and f02 in (select user_id from s61.t_user_capital_account where status="+"'YWC'))";
		    ResultSet sr=statement.executeQuery(sql);
		    System.out.println("執行結果如下所示");
		    
		    while (sr.next())
		    {
		    	loginname=sr.getString("f02");
		    	
		    	
		    }
		    sr.close();
		    con.close();
	    	
		}catch(ClassNotFoundException e){
			System.out.println("sorry,not found sqlDriver");;
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			System.out.println("資料查詢成功");
		} 
		return loginname;
	}
}

查詢結果為 :