Before we do any operation for database , we should know how to connect the Mysql database
throuth JDBC.
The example is as below :
import java.sql.*;
public class DBConnectionDemo
{
public static void main(String[] args)
{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/GUESTBOOK";
String user = "root";
String password = "123456";
try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
if(conn != null && !conn.isClosed())
{
System.out.println("資料庫連線測試成功!");
conn.close();
}
}
catch(ClassNotFoundException e)
{
System.out.println("找不到驅動程式類別");
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
First , We should load the JDBC driver into the JVM environment , so we use the code :
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
Then , we can connect to the database , we tell JDBC driver the database we used , the ip address and port of our database ,
and we also tell him the database which we want to connect.
String url = "jdbc:mysql://localhost:3306/GUESTBOOK";
Connection conn = DriverManager.getConnection(url, user, password);
ref : http://caterpillar.onlyfun.net/Gossip/JavaGossip-V2/ConnectDB.htm
全站熱搜