通过java代码如何实现对mysql数据库进行创建新的数据库的操作
发布网友
发布时间:2022-04-07 19:00
我来回答
共2个回答
热心网友
时间:2022-04-07 20:29
1 import java.sql.Connection;
2 import java.sql.DriverManager;
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.sql.Statement;
6
7 public class CreateDataSource {
8
9 /**
10 * @param args
11 */
12 public static void main(String[] args) {
13 // TODO Auto-generated method stub
14 String database = "test2";
15 new CreateDataSource().getConn(database);
16 }
17
18 String mysqlDriver = "com.mysql.jdbc.Driver";
19 String url = "jdbc:mysql://localhost:3306/test1";
20 String newUrl = "jdbc:mysql://localhost:3306/";
21 String username = "root";
22 String password = "root";
23 Connection conn = null;
24 Connection newConn = null;
25
26 public Connection getConn(String database) {
27
28 try {
29 Class.forName(mysqlDriver);
30 } catch (ClassNotFoundException e) {
31 // TODO Auto-generated catch block
32 e.printStackTrace();
33 }
34 try {
35 String tableSql = "create table t_user (username varchar(50) not null primary key,"
36 + "password varchar(20) not null ); ";
37 String databaseSql = "create database " + database;
38
39 conn = DriverManager.getConnection(url, username, password);
40 Statement smt = conn.createStatement();
41 if (conn != null) {
42 System.out.println("数据库连接成功!");
43
44 smt.executeUpdate(databaseSql);
45
46 newConn = DriverManager.getConnection(newUrl + database,
47 username, password);
48 if (newConn != null) {
49 System.out.println("已经连接到新创建的数据库:" + database);
50
51 Statement newSmt = newConn.createStatement();
52 int i = newSmt.executeUpdate(tableSql);//DDL语句返回值为0;
53 if (i == 0) {
54 System.out.println(tableSql + "表已经创建成功!");
55 }
56 }
57 }
58
59 } catch (SQLException e1) {
60 // TODO Auto-generated catch block
61 e1.printStackTrace();
62 }
63 return conn;
64 }
65 }
热心网友
时间:2022-04-07 21:47
使用Statement 或PreparedStatement去执行SQL。。。。。。
CREATE DATABASE test1234