import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestMysqlConnection {
/**
* 连接mysql数据库
* @param args
*/
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功");
//2.指定连接协议
String url = "jdbc:mysql://127.0.0.1:3306/jdbcdb";
String user = "root";
String pwd = "";
//3.建立数据库连接
conn = DriverManager.getConnection(url,user,pwd);
System.out.println("数据库连接成功");
//4.获取数据库操作对象
stmt = conn.createStatement();
//5.定义要执行的sql
String sql = "create table t_first" +
"(id int(5),name varchar(50))";
int ret = stmt.executeUpdate(sql);//执行SQL语句
if (ret==0){
System.out.println("建表成功!");
}
//6.捕获异常
} catch (Exception e) {
e.printStackTrace();
} finally{
//7.关闭对象,释放资源
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn !=null){
try {
if (!conn.isClosed()){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
以上只是基本的开发步骤. |
|