2016-04-11 83 views
0

我对MySQL非常陌生,并且很好奇我怎样才能在MySQL中创建一个具有所需列的表我想如果它不存在使用JavaJava在MySQL中使用列创建表

Visual of what I'd like

+1

开始与[JDBC数据库访问(http://docs.oracle.com/javase/tutorial/jdbc/)和[CREATE TABLE语法](http://dev.mysql.com/doc/ refman/5.7/en/create-table.html) – MadProgrammer

回答

0

下面的代码被写入做的正是你想要的。您必须使用JDBC mySQL驱动程序通过java连接到mySQL服务器。希望这可以帮助。

//assuming that you are using JDBC connector for mysql 
Class.forName("com.mysql.jdbc.Driver"); 

//connect to mysql server. We are using a class in the imported java mysql library to establish a connection with the mysql database server 
//root is the username, next parameter is the password. 
connection = DriverManager.getConnection("jdbc:mysql://localhost/?", "root", ""); 

//ceeate a statement to be executed in the mysql database server. 
Statement statement = connection.createStatement(); 

//create database if it doesn't exist 
//That is, sending a create table mysql command to the database server. 
statement.execute("CREATE DATABASE IF NOT EXISTS sheetdata"); 

//create table if it doesn't exist. This was a example I used. You can change the table definition as you want. 
//this will send the create table sql statement to be executed in the mysql server 
statement.execute("CREATE TABLE IF NOT EXISTS sheetdata.`saveddata` (\n" 
     + " `INDEX` int(10) NOT NULL AUTO_INCREMENT,\n" 
     + " `FILENAME` varchar(100) DEFAULT NULL,\n" 
     + " `TABLENAME` varchar(100) DEFAULT NULL,\n" 
     + " `TIMESTAMP` varchar(50) DEFAULT NULL,\n" 
     + " PRIMARY KEY (`INDEX`)\n" 
     + ") ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;"); 
connection.close(); 
+0

你介意告诉我执行代码的每一行是干什么的吗? – MrExporting24

+0

增加了一些更多的评论供你理解。你最好搜索并找到更多关于java mysql连接库的信息。这将有助于你了解更多。 –

+1

这里你去http://www.tutorialspoint.com/jdbc/jdbc-create-tables.htm – kakurala