» 首頁 » 討論區 » 程式設計討論 »Java使用JDBC操作MySQL

Java使用JDBC操作MySQL

發表人: Seachaos
積分: 2432
發表時間: 2010-04-24 22:47:48
怕自己忘記怎麼操作JDBC,在這邊做個筆記
[quote]
import java.sql.*;

import com.mysql.jdbc.Driver;

public class LikePHP2MySQL{
    public String
        ServerAddress = "localhost",
        ServerAccount = "root",
        ServerPassword = "",
        ServerDatabase = "",
        ServerPort = "3306",
        ServerEncode = "utf8",
        ServerType = "mysql";
    public Connection con;
    public ResultSet result;
    public void connect(){
         try {
            String jdbcStr = "jdbc:"+
                ServerType+"://"+
                ServerAddress+":"+
                ServerPort+"/"+
                ServerDatabase+"?useUnicode=true&characterEncoding="+
                ServerEncode;
            con = DriverManager.getConnection( jdbcStr,ServerAccount,ServerPassword);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
    public void voidQuery(String sql){
        try {
            Statement server;
            server = con.createStatement();
            server.execute(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public ResultSet query(String sql){
        Statement server;
        try {
            server = con.createStatement();
            ResultSet result = server.executeQuery(sql);
            this.result = result;
            return result;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.print("Query Error!");
            e.printStackTrace();
            return null;
        }
    }
}

[/quote]
其中import com.mysql.jdbc.Driver需要include額外的Library(MySQL的Driver)到Java內

Ubuntu如果有安裝libmysql-java
可以在/usr/share/java底下找到mysql.jar