在电脑已经安装mysql, 以及相关的配置,然后下载Mysql连接驱动程序, 下载连接驱动程序.
把驱动程序导入应用程序中,步骤是在项目名上单击鼠标右键, 选择"build path",再选择“add External Archivers…”,再选择加载的驱动,驱动程序导入之后,在该项目下出现"Referenced Libraries"。
数据库连接类DBConnection.java:
package com.myjdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private String driver = "com.mysql.cj.jdbc.Driver";
private String conurl = "jdbc:mysql://localhost:3306/mydb?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=GMT";
private String username = "root";
private String userpasswd = "123456";
private Connection connection = null;
public Connection getConnection() {
// TODO Auto-generated constructor stub
try {
Class.forName(driver);
System.out.println("driver success!");
connection = DriverManager.getConnection(conurl, username, userpasswd);
System.out.println("Connection success!");
} catch (ClassNotFoundException e) {
// TODO: handle exception
System.out.println("driver failure!");
}catch (SQLException e) {
// TODO: handle exception
System.out.println("connection failure!");
e.printStackTrace();
}
return connection;
}
public void closeConnection(){
if (connection != null)
{
try {
connection.close();
System.out.println("close database success!");
} catch (SQLException e) {
// TODO: handle exception
System.out.println("close failure!");
}
}
}
}
数据库表的创建CreateTable.java:
package com.myjdbc;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTable {
private Connection con = null;
private Statement stmt = null;
public CreateTable() {
// TODO Auto-generated constructor stub
}
public boolean createBookDataTable(){
DBConnection onecon= new DBConnection();
con = onecon.getConnection();
boolean returnResult = true;
try {
stmt = con.createStatement();
String pSql = "create table student (sno char(10), sname char(20), sage integer, smajor char(10))";
stmt.execute(pSql);
stmt.close(); // 释放Statement 所连接的数据及JDBC资源
con.close(); //关闭与数据库的链接
} catch (SQLException e) {
// TODO: handle exception
returnResult = false;
e.printStackTrace();
}
return returnResult;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CreateTable c = new CreateTable();
boolean isSuccess = c.createBookDataTable();
if (isSuccess)
System.out.println("The table is createed.");
else {
System.out.println("The table is not createed.");
}
}
}
运行程序结果为: