这个例子主要介绍jdbc连接mysql数据库。
step 1: 下载MySQL JDBC Driver下载地址:
MySQL JDBC Driver Download Herestep 2: java JDBC连接mysql实例jdbc连接mysql的代码:
- Class.forName("com.mysql.jdbc.Driver");
-
Connection connection = null;
-
connection = DriverManager.getConnection(
-
"jdbc:mysql://hostname:port/dbname","username", "password");
-
connection.close();
查看一个完整的实例:
(记得引入step 1 下载的driver: mysql-connector-java-x.x.x-bin.jar)
文件: JDBCConnectMySQL.java
- package org.hnrsc.jdbc;
-
-
import java.sql.Connection;
-
import java.sql.DriverManager;
-
import java.sql.SQLException;
-
-
public class JDBCConnectMySQL {
-
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) {
-
System.out.println("-------- MySQL JDBC Connection Testing ------------");
-
try{
-
Class.forName("com.mysql.jdbc.Driver");
-
}catch(ClassNotFoundException e){
-
System.out.println("Can't find the MySQL JDBC Driver");
-
e.printStackTrace();
-
return;
-
}
-
-
System.out.println("MySQL JDBC Driver Registered!");
-
Connection conn = null;
-
-
try{
-
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "");
-
}catch(SQLException e){
-
System.out.println("Connection Failed! Check output console");
-
e.printStackTrace();
-
return;
-
}
-
-
if (conn != null) {
-
System.out.println("You made it, take control your database now!");
-
} else {
-
System.out.println("Failed to make connection!");
-
}
-
}
-
-
}
step 3:运行
你可能会看到以下结果:
- -------- MySQL JDBC Connection Testing ------------
-
MySQL JDBC Driver
-
You made it, take control your database
阅读(1022) | 评论(0) | 转发(0) |