为了避免打关键字出错,特意写的工具类
/**
* SQL字符串追加器
* @author Sam
*
*/
public class SQLBuilder
{
private StringBuilder builder;
private final String TAB = " ";
public SQLBuilder()
{
builder = new StringBuilder();
}
public SQLBuilder addSQL(String value)
{
builder.append(TAB+value+TAB);
return this;
}
/**
* 添加左括号
* @return
*/
public SQLBuilder addLeftBracket()
{
builder.append("(");
return this;
}
/**
* 添加integer类型
* @return
*/
public SQLBuilder addInt()
{
this.addSQL("integer");
return this;
}
/**
* 添加text类型
* @return
*/
public SQLBuilder addText()
{
this.addSQL("text");
return this;
}
/**
* 追加varchar
* @param len 长度
* @return
*/
public SQLBuilder addVarchar(int len)
{
this.addSQL("varchar").addLeftBracket().add(len).addRightBracket();
return this;
}
/**
* 添加右括号
* @return
*/
public SQLBuilder addRightBracket()
{
builder.append(")");
return this;
}
/**
* 添加逗号
* @return
*/
public SQLBuilder addComma()
{
builder.append(",");
return this;
}
/**
* 追加not null
* @return
*/
public SQLBuilder addNotNull()
{
this.addSQL("not null");
return this;
}
public SQLBuilder addNull()
{
this.addSQL("null");
return this;
}
public SQLBuilder addPrimarykey()
{
this.addSQL("primary key");
return this;
}
public SQLBuilder add(Object value)
{
builder.append(value);
return this;
}
/**
* 添加自增长字段
* @return
*/
public SQLBuilder addAutoincrement()
{
this.addSQL("autoincrement");
return this;
}
/**
* "create table if not exists"
* @return
*/
public SQLBuilder addCreateTableIfNotExists()
{
this.addSQL("create table if not exists");
return this;
}
/**
* 添加属性字段
* @param element
* @return
*/
public SQLBuilder addElement(String element)
{
this.addSQL(element);
return this;
}
public String toString()
{
return builder.toString();
}
}
--------------------------------------------------------------------------------------------------------------------------------------
public static void main(String[] args)
{
SQLBuilder builder = new SQLBuilder();
builder.addCreateTableIfNotExists().addElement("student");
builder.addLeftBracket();
builder.addElement("id").addInt().addNotNull().addPrimarykey().addAutoincrement().addComma();
builder.addElement("age").addInt().addNull().addComma();
builder.addElement("name").addVarchar(25).addNull().addComma();
builder.addElement("info").addText().addNull();
builder.addRightBracket();
System.out.println(builder);
}
---------------------------------------------------------------------------------------------