一、创建MySQL.Ini文件
在新建项目src下创建mysql.ini文件,选择文本文件
目录结构如下:
二、编辑mysql.ini文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/user
user=root
pass=root
三、创建工具类ConnectMysql
代码如下:
package com.createTable.mysqlCreate;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;
public class ConnectMysql {
private String driver;
private String url;
private String user;
private String pass;
Connection conn;
Statement stmt;
public void initParam(String paramFile) throws Exception {
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
}
public void createTale(String sql) throws Exception {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pass);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} finally {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
}
}
四、创建测试类ConnectMysqlTest
代码如下:
package com.createTable.mysqlCreate;
public class ConnectMysqlTest {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ConnectMysql ed = new ConnectMysql();
ed.initParam("src/mysql.ini");
ed.createTale("create table user " +
"(id int, " +
"name varchar(50), " +
"num varchar(20) )");
System.out.println("Creating table success!");
}
}
五、运行结果
Creating table success!
六、展示
代码git地址
https://gitee.com/rosyclouds-sss/CreateTable