import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.sql.*;
import java.util.PropertyResourceBundle;
public class MySqlConnector {
/*
* 先在项目bin目录下新建一个dbCon.ini文件
* 内容 如下,注意大小写:
* userName=你的数据库用户名
* password=你的数据库用户密码
* database=要连接的数据库名称
*/
private static final String CON_NAME = "userName";
private static final String CON_PASS = "password";
private static final String CON_DNAME = "databaseName";
private Connection connection = null;
private MySqlConnector() {
}
public static MySqlConnector getInstance() {
return new MySqlConnector();
}
private boolean dataInit() {
boolean isOK = false;
String userName = "";
String password = "";
String databaseName = "";
PropertyResourceBundle rBoundle = null;
try {
String conPath = MySqlConnector.class.getResource("/").toString() + "/dbCon.ini";
URI uri = new URI(conPath);
File file = new File(uri);
rBoundle = new PropertyResourceBundle(new FileInputStream(file));
userName = rBoundle.getString(MySqlConnector.CON_NAME);
password = rBoundle.getString(MySqlConnector.CON_PASS);
databaseName = rBoundle.getString(MySqlConnector.CON_DNAME);
String url;
url = "jdbc:mysql://localhost/" + databaseName + "?user="
+ userName + "&password=" + password;
System.out.println(url);
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url);
isOK = true;
} catch (Exception e) {
e.printStackTrace();
isOK = false;
}
return isOK;
}
public Connection getConnection() {
if (dataInit()) {
return connection;
} else {
return null;
}
}
public void close() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
import java.sql.*;
import javax.swing.*;
public class HH {
static Connection con=null;
public static boolean conn(String url,String username,String password){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch(Exception e){e.printStackTrace();return false;}
try{
con=DriverManager.getConnection(url,username,password);
}catch(SQLException e){e.printStackTrace();return false;}
return true;
}
public static boolean close(){
try{
con.close();
con=null;
}catch(SQLException e){e.printStackTrace();return false;}
return true;
}
public static void main(String args[]){
if(conn("jdbc.odbc:myuser","system","admin")){
JOptionPane.showMessageDialog(null, "连接数据库成功!");
close();
}
else{
JOptionPane.showMessageDialog(null, "数据库连接失败!!");
}
}
}
直接拷进去Run就可以了
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://host:port/database","user","password");
host:port : 数据库地址
database : 端口号
user : 用户名
password : 密码
。。。所有书上都有些 问以前翻翻书好么
官方教材:
http://java.sun.com/docs/books/tutorial/jdbc/index.html