Eclipse連接MySQL進行順序查詢

花了整整一天裝配JDBC、MySQL還有相應的組件,其中報出各種bug。通過各路神仙相救,終於是在晚上一邊和女友看美劇,一邊給調試成功了!激動!下面就讓我們瞧瞧代碼!

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

public class zz{
	public static void main(String args[]) {
		Statement sql;
		ResultSet rs;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver"); 			//加載JDBC-MySQL驅動
		}catch(Exception e){}
		
		try {
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/students?serverTimezone=GMT&&useSSL=true","root","123456");
			sql = con.createStatement();
			rs = sql.executeQuery("SELECT * FROM mess"); 	//查詢mess表
			while(rs.next()) {
				String number = rs.getString(1);
				String name = rs.getString(2);
				Date date = rs.getDate(3);
				float height = rs.getFloat(4);
				System.out.printf("%s\t",number);
				System.out.printf("%s\t",name);
				System.out.printf("%s\t",date);
				System.out.printf("%.2f\n",height);
			}
			con.close();
		}catch(SQLException e) {
			System.out.println(e);
		}
		
	}
}

問題

  1. 最主要的是配置jdbc,將jar包放進path中;
  2. 最近的版本都要用com.mysql.cj.jdbc.Driver;
  3. 下午調試了很久但是沒有創建一個對應的數據庫,晚上問了老師才知道,於是用navicat創了一個students數據庫;
  4. 注意看報錯信息;
  5. 要將Connection con的申明和rs,sql使用放在一起。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章