Mysql-jdbc典型案例-要背誦
阿新 • • 發佈:2018-12-17
package day10yue22; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class ExcuteDDL { private String driver; private String url; private String user; private String pass; public void initParam(String paramFile) throws FileNotFoundException, IOException { Properties props = new Properties(); props.load(new FileInputStream(paramFile)); driver = props.getProperty("jdbc.driverClassName"); url = props.getProperty("jdbc.url"); user = props.getProperty("jdbc.username"); pass = props.getProperty("jdbc.password"); } public void createTable(String sql) throws SQLException, ClassNotFoundException { Class.forName(driver); Connection conn = DriverManager.getConnection(url,user,pass); Statement stmt = conn.createStatement(); stmt.execute(sql); } public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException { ExcuteDDL ed = new ExcuteDDL(); ed.initParam("d:\\mysql.ini"); ed.createTable("create table jdbc_test(id int); "); System.out.println("建表成功"); } }
mysql.ini檔案的內容:
jdbc.driverClassName = com.mysql.cj.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/zou?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false jdbc.username = root jdbc.password = ""