his example demonstrates how to create a table in JDBC in MySQL database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCCreateTable {
private static final String DBURL =
"jdbc:mysql://localhost:3306/mydb?user=usr&password=sql&" +
"useUnicode=true&characterEncoding=UTF-8";
private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
static {
try {
Class.forName(DBDRIVER).newInstance();
} catch (Exception e){
e.printStackTrace();
}
}
private static Connection getConnection()
{
Connection connection = null;
try {
connection = DriverManager.getConnection(DBURL);
}
catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static void main(String[] args) {
Connection con = getConnection();
Statement stmt =null;
String createString;
createString = "CREATE TABLE `mydb`.`employees` ("+
"`EmployeeID` int(10) unsigned NOT NULL default '0',"+
"`Name` varchar(45) collate utf8_unicode_ci NOT NULL default '',"+
"`Office` varchar(10) collate utf8_unicode_ci NOT NULL default '',"+
"`CreateTime` timestamp NOT NULL default CURRENT_TIMESTAMP,"+
"PRIMARY KEY (`EmployeeID`)"+
") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
}
}
}
No comments:
Post a Comment