java串連MySql資料庫!
來源:互聯網
上載者:User
package com.roytel.rtccp.util;
import java.sql.*;
public class DBManager {
//使用者名稱
private String user = "";
//密碼
private String password = "";
//主機
private String host = "";
//資料庫名字
private String database = "";
/*
private String url="jdbc:mysql://"+host+"/"+"useUnicode=true&characterEncoding=GB2312";
*/
private String url ="";
private Connection con = null;
Statement stmt;
/**
* 根據主機、資料庫名稱、資料庫使用者名稱、資料庫使用者密碼取得串連。
* @param host String
* @param database String
* @param user String
* @param password String
*/
public DBManager(String host, String database, String user, String password) {
this.host = host;
this.database = database;
this.user = user;
this.password = password;
//顯示中文
this.url = "jdbc:mysql://" + host + "/" + database +
"?useUnicode=true&characterEncoding=GB2312";
try {
Class.forName("org.gjt.mm.mysql.Driver");
}
catch (ClassNotFoundException e) {
System.err.println("class not found:" + e.getMessage());
}
try {
con = DriverManager.getConnection(this.url, this.user, this.password);
//連線類型為ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch (SQLException a) {
System.err.println("sql exception:" + a.getMessage());
}
}
/**
* 返回取得的串連
*/
public Connection getCon() {
return con;
}
/**
* 執行一條簡單的查詢語句