最近在學習數據庫開發的一些實例,這裡淺談一下用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()); } }}
輕松搞定,一下為輸出結果: