文后附有完整Eclipse工程的链接
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.b3log.latke.Latkes;
import org.b3log.latke.repository.jdbc.*;
import org.b3log.latke.repository.mysql.*;
import org.b3log.latke.repository.jdbc.util.*;
public class testCreateTable {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Latkes.initRuntimeEnv();
FieldDefinition pu=new FieldDefinition();
List<FieldDefinition> chu=new ArrayList<FieldDefinition>();
pu.setName("liusir");
pu.setType("String");
pu.setLength(50);
pu.setIsKey(true);//如果只有一个字段,此处必须设置成true,否则sql语句有语法错误
chu.add(pu);
JdbcFactory aProduct=JdbcFactory.createJdbcFactory();
try {
aProduct.createTable("zhaoJiaChen",chu);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public abstract class AbstractJdbcDatabaseSolution implements JdbcDatabase {
/**
* the map Mapping type to real database type.
*/
private Map<String, Mapping> jdbcTypeMapping = new HashMap<String, Mapping>();
/**
*
* register type to mapping solution.
*
* @param type type from json
* @param mapping {@link Mapping}
*/
public void registerType(final String type, final Mapping mapping) {
jdbcTypeMapping.put(type, mapping);
}
@Override
public boolean createTable(final String tableName, final List<FieldDefinition> fieldDefinitions) throws SQLException {
final Connection connection = Connections.getConnection();
try {
// need config
// final StringBuilder dropTableSql = new StringBuilder();
// createDropTableSql(dropTableSql, tableName);
// JdbcUtil.executeSql(dropTableSql.toString(), connection);
final StringBuilder createTableSql = new StringBuilder();
createTableHead(createTableSql, tableName);
createTableBody(createTableSql, fieldDefinitions);
createTableEnd(createTableSql);
//刘利新check
System.out.println("刘利新check sql");
System.out.println(createTableSql);
return JdbcUtil.executeSql(createTableSql.toString(), connection);
} catch (final SQLException e) {
throw e;
} finally {
connection.close();
}
}
上面第36行的输出为:
刘利新check sql
CREATE TABLE IF NOT EXISTS zhaoJiaChen(liusir varchar(50), PRIMARY KEY(liusir)) ENGINE= InnoDB DEFAULT CHARSET= utf8;
源代码:http://pan.baidu.com/share/link?shareid=1777829223&uk=3878681452