Last active
November 30, 2016 07:33
-
-
Save Wonicon/aff8209a85dc823393f8649042ae67f0 to your computer and use it in GitHub Desktop.
Create sql insert statement from GBK priliminary tuple description, seperated by "、", and auto add quotation marks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Input sample: | |
* | |
* TableName | |
* (1,样例,example)、(2,样例,example) | |
* ; | |
* EOF | |
* | |
* Output: | |
* insert into TableName values (1, "样例", "example"); | |
* insert into TableName values (2, "样例", "example"); | |
*/ | |
import java.util.Scanner; | |
public class DBTrick { | |
public static String quote(String sql) { | |
StringBuilder sb = new StringBuilder(); | |
int state = 0; // 1 - (...), 2 - "..." | |
for (char ch : sql.toCharArray()) { | |
switch (state) { | |
case 0: | |
sb.append(ch); | |
if (ch == '(') { | |
state = 1; | |
} | |
break; | |
case 1: | |
if (ch == ',' || ch == ' ' || ch == ';' || ch == ')' || Character.isDigit(ch)) { | |
sb.append(ch); | |
} | |
else { | |
sb.append('\''); | |
sb.append(ch); | |
state = 2; | |
} | |
break; | |
case 2: | |
if (ch == ',' || ch == ' ' || ch == ';' || ch == ')' || Character.isDigit(ch)) { | |
sb.append('\''); | |
sb.append(ch); | |
state = 1; | |
} | |
else { | |
sb.append(ch); | |
} | |
break; | |
} | |
} | |
return sb.toString(); | |
} | |
public static void main(String[] args) { | |
Scanner input = new Scanner(System.in); | |
while (input.hasNext()) { | |
String table = input.next(); | |
while (input.hasNext()) { | |
String line = input.nextLine(); | |
if (line.equals(";")) { | |
break; | |
} | |
for (String tuple : line.split("、")) { | |
String sql = tuple | |
.replace("(", "insert into " + table + " values (") | |
.replace(")", ");") | |
.replace(",", ", "); | |
System.out.println(quote(sql)); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment