首先呢,你必須先架設網頁伺服器(WAMP、Appserv...都可以)
在這裡我想著重在java如何與mysql連線,所以如何架設伺服器我不想在這裡贅述
相信google上有許多教學的~或者是你可以參考我這一篇的教學(點這)
伺服器架設好以後,要先去下載java mysql driver
下載JDBC Driver for MySQL
下載完解壓縮以後注意這個jar檔
建立java 專案,建好以後
在JRE System library中點選Build path接著點選Configure Build Path
接著點選Add External JARS 把剛剛你載下來的那個jar檔加進來
加進來以後就可以開始寫程式了
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package database; | |
import java.sql.*; | |
public class Main { | |
public static void main(String[] args) { | |
DBConnect connection=new DBConnect(); | |
connection.getData(); | |
} | |
} | |
class DBConnect{ | |
private Connection con; | |
private Statement st; | |
private ResultSet rs; | |
public DBConnect() { | |
try { | |
//Class 的靜態 forName() 方法實現動態加載類別 | |
Class.forName("com.mysql.jdbc.Driver"); | |
//3306|MySQL開放此端口 | |
con= DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb","root","root"); | |
st= con.createStatement(); | |
}catch(Exception ex){ | |
System.out.println("Error: "+ex); | |
} | |
} | |
public void getData() { | |
try { | |
String query = "select * from testTable"; | |
rs = st.executeQuery(query); | |
System.out.println("Records for Database"); | |
while(rs.next()) { | |
int id = rs.getInt("id"); | |
String name = rs.getString("name"); | |
System.out.println("id= "+id+" name= "+name); | |
} | |
}catch(Exception ex) { | |
System.out.println(ex); | |
} | |
} | |
} |
文章標籤
全站熱搜