最近在學習數據庫開發的一些實例,這里淺談一下用JDBC連接數據庫MySQL(當然也可以連接SQL Sever或Oracle了,只是我更喜歡開源軟件,同時也更簡單)。
首先正確安裝好MySQL,建立好數據庫studentinfo
mysql>create database studentinfo; |
然后編寫java代碼,ConnectToMySQL.java
import java.sql.*;public class ConnectToMySQL { public static Connection getConnection() throws SQLException , java.lang.ClassNotFoundException{ String url = "jdbc:mysql://localhost:3306/studentinfo"; Class.forName("com.mysql.jdbc.Driver"); String userName = "root"; String password = ""; Connection con = DriverManager.getConnection(url,userName,password); return con; } public static void main(String[] args) { try{ Connection con = getConnection(); Statement sql = con.createStatement(); sql.execute("drop table if exists student"); sql.execute("create table student(id int not null auto_increment,name varchar(20) not null default 'name',math int not null default 60,primary key(id));"); sql.execute("insert student values(1,'AAA','99')"); sql.execute("insert student values(2,'BBB','77')"); sql.execute("insert student values(3,'CCC','65')"); String query = "select * from student"; ResultSet result = sql.executeQuery(query); System.out.println("Student表數據如下:"); System.out.println("---------------------------------"); System.out.println("學號"+" "+"姓名"+" "+"數學成績"); System.out.println("---------------------------------"); int number; String name; String math; while(result.next()){ number = result.getInt("id"); name = result.getString("name"); math = result.getString("math"); System.out.println(number + " " + name + " " + math); } sql.close(); con.close(); }catch(java.lang.ClassNotFoundException e){ System.err.println("ClassNotFoundException:" + e.getMessage()); }catch(SQLException ex){ System.err.println("SQLException:" + ex.getMessage()); } }} |
輕松搞定,一下為輸出結果:

要注意的是使用MySQL數據庫,需要用到對應的JDBC驅動程序mysql-connector-java-5.0.3,可以到zySQL的官方網站上下載(http://www.mysql.org)
作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
※以上資訊由網路資料整理而成,若有遺誤概以來源為準,本站不負任何相關責任。
※如果您認為網站上資訊侵犯了您的版權,請告訴我們
按這裡,我們將即時將您的版權資料移除。