1.首先準備mysql 和eclipse環(huán)境,在環(huán)境搭建好之后,從eclipse官網(wǎng)下載jdbc的驅(qū)動包,下載地址http://dev.mysql.com/downloads/connector/j/
2.從下載的文件中取出mysql-connector-java-5.1.31-bin.jar,放到工程中,并導(dǎo)入路徑
方法:右擊工程名->Build Path->Configure Build Path,選擇Add External JAR... 找到mysql-connector-java-5.1.31-bin.jar所在的位置,然后將驅(qū)動包加載到項目中,
3.寫個例子測試一下
package testmysql; import java.sql.*; public class Test { public static void main(String[] args) { String driver = "com.mysql.jdbc.Driver"; String URL = "jdbc:mysql://localhost:3306/student"; Connection con = null; try { Class.forName(driver); } catch(java.lang.ClassNotFoundException e) { System.out.println("Connect Successfull."); System.out.println("Cant't load Driver"); } try { con=DriverManager.getConnection(URL,"root","root"); System.out.println("Connect Successfull."); } catch(Exception e) { System.out.println("Connect fail:" + e.getMessage()); } } }
連接上數(shù)據(jù)庫之后,可以根據(jù)表中的內(nèi)容進行數(shù)據(jù)庫表的查詢,首先表中要有內(nèi)容,將一些信息輸入到表中之后即可使用SQL語言進行查詢
import java.sql.*; public class Main { public static void main(String[] args) { String driver = "com.mysql.jdbc.Driver"; String URL = "jdbc:mysql://localhost:3306/xiaolu"; Connection con = null; ResultSet rs = null; Statement st = null; String sql = "select * from student"; try { Class.forName(driver); } catch(java.lang.ClassNotFoundException e) { // System.out.println("Connect Successfull."); System.out.println("Cant't load Driver"); } try { con=DriverManager.getConnection(URL,"root","root"); st=con.createStatement(); rs=st.executeQuery(sql); if(rs!=null) { ResultSetMetaData rsmd = rs.getMetaData(); int countcols = rsmd.getColumnCount(); for(int i=1;i=countcols;i++) { if(i>1) System.out.print(";"); System.out.print(rsmd.getColumnName(i)+" "); } System.out.println(""); while(rs.next()) { System.out.print(rs.getString("sno")+" "); System.out.print(rs.getString("sname")+" "); System.out.print(rs.getString("ssex")+" "); System.out.print(rs.getString("sage")+" "); System.out.println(rs.getString("sdept")+" "); } } //System.out.println("Connect Successfull."); System.out.println("ok"); rs.close(); st.close(); con.close(); } catch(Exception e) { System.out.println("Connect fail:" + e.getMessage()); } } }
關(guān)于JDBC連接MySQL5.7的文章就介紹到這,其他的可以查下腳本之家其它相關(guān)文章。