List to quoted string - dart

I need to convert List to quoted string. My code is:
void main() {
List<String> list = ["aa", "bb", "cc"];
String str = "INSERT INTO (" + list.toString() + ") VALUES (...) ";
print(str);
}
output:
INSERT INTO ([aa, bb, cc]) VALUES (...)
But I need:
INSERT INTO ("aa", "bb", "cc") VALUES (...)

void main() {
List<String> list = ["aa", "bb", "cc"];
String str =
"INSERT INTO (" + list.map((e) => '"$e"').join(', ') + ") VALUES (...) ";
print(str); // INSERT INTO ("aa", "bb", "cc") VALUES (...)
}
Can also be done like this which are a little shorter:
void main() {
List<String> list = ["aa", "bb", "cc"];
String str =
"INSERT INTO (${list.map((e) => '"$e"').join(', ')}) VALUES (...) ";
print(str); // INSERT INTO ("aa", "bb", "cc") VALUES (...)
}
I should add that this is just a solution for solving your specific problem. For real SQL escaping from unknown input, you should take into account that the String can contain " and need to escape it correctly.

Related

How can I insert data inside parentheses? Dart

There are inputs:
String SQL = "INSERT INTO table () VALUES ()";
List data1 = ['user_id', 'user_name'];
List data2 = ['1', 'test']
How can I get "INSERT INTO table (user_id, user_name) VALUES (1, test)"? Thank you.
You can do this with String interpolation ${}
void main() {
List data1 = ['user_id', 'user_name'];
List data2 = ['1', 'test'];
String SQL = "INSERT INTO table (${data1[0]}, ${data1[1]}) VALUES (${data2[0]}, ${data2[1]})";
print(SQL);
}
DartPad sample: https://dartpad.dev/?id=39a56cbf2b5cab254902ac7aa3a4324f

Combining multiple items by condition within a single list

As in Dart you can combine several list items into one according to the following condition:
Given List<String> arr = ['2','3','b','*','4','5','6','-','3','4'];
Get arr = ['23','b','*','456','-','34'];
The list is unknown in advance. It can be of any length and with any sequence of characters. And need to combine only the lines that have numbers in them.
I would be grateful for any suggestions.
You are not describing what should happen if there are multiple special characters or letters. So I have made my example so it will only combine numbers:
void main() {
final arr = ['2', '3', 'b', '*', '4', '5', '6', '-', '3', '4'];
print(combine(arr)); // [23, b, *, 456, -, 34]
}
List<String> combine(List<String> input) {
final output = <String>[];
final buffer = StringBuffer();
for (final string in input) {
if (int.tryParse(string) == null) {
if (buffer.isNotEmpty) {
output.add(buffer.toString());
buffer.clear();
}
output.add(string);
} else {
buffer.write(string);
}
}
if (buffer.isNotEmpty) {
output.add(buffer.toString());
}
return output;
}
You can use ''.join() here:
arr = [''.join(arr[0:2]), arr[2], arr[3], ''.join(arr[4:7]), arr[7], ''.join(arr[8:10])]
If you only want to have a condition where you only join numerical values then you can add a for loop beforehand.

Getting stackoverflow on recursion

I want to generate INSERT statement from JSON. The problem that I have problem with recursion (in section where I am getting nested elements). it's seems that I am getting SO.
import 'dart:convert';
main() {
Map jsonMap = jsonDecode(
'{"id":"1","name":"sample","Lots":[{"id":"1","title":"books","objs":[{"book":"name"}]}]}');
KVToTableInsert(String tablename, Map jsonMap) {
List<String> insertNoticeKeys = [];
List<String> insertNoticeValues = [];
jsonMap.forEach((key, value) {
if (value is List) // nested
{
KVToTableInsert(key, jsonMap); // if comment this line all work
} else {
insertNoticeKeys.add(key);
insertNoticeValues.add(value);
}
});
String sql = "INSERT INTO $tablename (" +
insertNoticeKeys.map((e) => '"$e"').join(', ') +
") VALUES (" +
insertNoticeValues.map((e) => "'$e'").join(', ') +
")";
print(sql);
}
KVToTableInsert("RootTable", jsonMap);
}
I expected to get 3 INSERT statment:
INSERT INTO RootTable ("id", "name") VALUES ('1', 'sample')
INSERT INTO Lots ("id", "title") VALUES ('1', 'books')
INSERT INTO Objs ("book") VALUES ('name')
But I am getting crush on this app.
There was a slight problem in your code, basically in this part:
if (value is List){
KVToTableInsert(key, jsonMap); // if comment this line all work
}
If you closely, take a look at your KVToTableInsert, you're passing arguments Map and not list. Which fails your recursion.
What you need to do is to pass the item of the array, into your KVToTableInsert, and this will work as expected
FINAL SOLUTION
// taking your jsonMap directly, and not decoding it
void main() {
Map jsonMap = {
"id":"1",
"name":"sample",
"Lots":[
{
"id": "1",
"title":"books",
"objs":[
{
"book":"name"
}
]
}
]
};
void KVToTableInsert(tablename, jsonMap){
List<String> insertNoticeKeys = [];
List<String> insertNoticeValues = [];
jsonMap.forEach((key,value){
if (value is List)
{
// Here is the magic, you need to iterate over your list, and pass MAP, not LIST
value.forEach((item){ KVToTableInsert(key, item);});
} else {
insertNoticeKeys.add(key);
insertNoticeValues.add(value);
}
});
String sql = "INSERT INTO $tablename (" +
insertNoticeKeys.map((e) => '"$e"').join(', ') +
") VALUES (" +
insertNoticeValues.map((e) => "'$e'").join(', ') +
")";
print(sql);
}
KVToTableInsert("Rootable", jsonMap);
}
OUTPUT
INSERT INTO objs ("book") VALUES ('name')
INSERT INTO Lots ("id", "title") VALUES ('1', 'books')
INSERT INTO Rootable ("id", "name") VALUES ('1', 'sample')
Also, look at the Dart Programming Language Naming Conventions, it is a good practise to use lowerCamelCase for your function/method name.

how to insert new row by using executeUpdate - FMdatabase

I'm using fmdb library.
https://github.com/ccgus/fmdb
I would like to insert new records but I don't know how can I do:
if let db = database, let q = db.executeUpdate("insert into \(table) (catid,subcat_id,id,subcat_title,title,description,lat,lon,takhfif,images,wifi,apple_health,wc,full_time,pos,work_hours,phone,mobile,fax,website,email,address,facebook,instagram,linkedin,telegram,googleplus,twitter,publish,feature,manager,city,rating_sum,rate_count,lastip,parking,isMallID,mallID,discount_images,price_images,newProduct_images,services_images,order_online,out_upon,cat_title,cat_icon,last_modify,item_logo,cat_logo,rate_sum1,rate_sum2,rate_sum3,rate_count1,rate_count2,rate_count3,rate_title1,rate_title2,rate_title3,rate_enable) values (\(catid),\(subcat_id),\(id),'\(subcat_title)','\(title)','\(description)','\(lat)','\(lon)','\(takhfif)','\(images)',\(wifi),\(apple_health),\(wc),\(full_time),\(pos),'\(work_hours)','\(phone)','\(mobile)','\(fax)','\(website)','\(email)','\(address)','\(facebook)','\(instagram)','\(linkedin)','\(telegram)','\(googleplus)','\(twitter)',\(publish),\(feature),'\(manager)','\(city)',\(rating_sum),\(rate_count),'\(lastip)',\(parking),\(isMallID),\(mallID),'\(discount_images)','\(price_images)','\(newProduct_images)','\(services_images)',\(order_online),\(out_upon),'\(cat_title)','\(cat_icon)',\(last_modify),'\(item_logo)','\(cat_logo)',\(rate_sum1),\(rate_sum2),\(rate_sum3),\(rate_count1),\(rate_count2),\(rate_count3),'\(rate_title1)','\(rate_title2)','\(rate_title3)',\(rate_enable))") {
}
but I got this message before building:
cannot invoke executeUpdate with an argument list of type string
You used the api wrong. The first parameter is the sql, each value has to be represented with an "?". The second one (values) is an array of the values. Try this:
if let db = database, let q = db.executeUpdate(
"insert into \(table) (catid,subcat_id,id,subcat_title,title,description,lat,lon,takhfif,images,wifi,apple_health,wc,full_time,pos,work_hours,phone,mobile,fax,website,email,address,facebook,instagram,linkedin,telegram,googleplus,twitter,publish,feature,manager,city,rating_sum,rate_count,lastip,parking,isMallID,mallID,discount_images,price_images,newProduct_images,services_images,order_online,out_upon,cat_title,cat_icon,last_modify,item_logo,cat_logo,rate_sum1,rate_sum2,rate_sum3,rate_count1,rate_count2,rate_count3,rate_title1,rate_title2,rate_title3,rate_enable) values (?, ?, ? ...., ?, ?, ? )"
values: [catid, subcat_id, id, subcat_title, title, description, lat, lon, takhfif, images, wifi, apple_health, wc, full_time, pos, work_hours, phone, mobile, fax, website, email, address, facebook, instagram, linkedin, telegram, googleplus, twitter, publish, feature, manager, city, rating_sum, rate_count, lastip, parking, isMallID, mallID, discount_images, price_images, newProduct_images, services_images, order_online, out_upon, cat_title, cat_icon, last_modify, item_logo, cat_logo, rate_sum1, rate_sum2, rate_sum3, rate_count1, rate_count2, rate_count3, rate_title1, rate_title2, rate_title3, rate_enable]) {
}
Note: I didn't count the values, so you have to ensure that the count of "?" inside of the string is exactly the count of your values!
Maybe you should think about a function to improve the readability of your code. Something like that:
extension FMDatabase {
func insert(into table: String, row values: [(column: String, content: Any)]) {
guard (values.count > 0) else { fatalError(values.count > 0, "Inserting nothing into a table makes no sense!") }
var sql = "INSERT INTO \(table) ("
var contents: [Any] = []
for (index, value) in values.enumerated() {
sql += index == 0 ? value.column : ", \(value.column)"
contents.append(value.content)
}
sql += ") VALUES ("
for index in 0..<values.count {
sql += index == 0 ? "?" : ", ?"
}
sql += ")"
executeUpdate(sql, values: contents)
}
}
Then you can insert values like that:
if let db = database {
db.insert(
into: table,
row: [
(column: "catid", content: catid),
(column: "subcat_id", content: subcat_id),
...
(column: "rate_enable", content: rate_enable)
]
)
}
Isn't it better readable?

joSQL query with double quotes parsing resulting org.josql.parser.TokenMgrError: Lexical error

Trying to run following code, in this the SQL statement trying to find values where colName2 like group/test" (name having double quote in the end), and passing the querySQL string to josql parser.
public static void main(String a[])
{
String querySQL = new String("Select * from tabName WHERE ((colName1) = ((\"type\" )) AND (colName2) LIKE ((\"%group/test\"%\" ))) ORDER BY colName2 asc");
org.josql.Query josql = new org.josql.Query();
try
{
josql.parse(querySQL);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println(josql.toString());
}
Following exception has been occurring when I run it, as colName2 contains a string with double quote in it. Does anyone has any idea on how to pass the double quote to josql parser?
Exception in thread "main" org.josql.parser.TokenMgrError: Lexical error at line 1, column 150. Encountered: after : "\" ))) ORDER BY colName2 asc"
at org.josql.parser.JoSQLParserTokenManager.getNextToken(JoSQLParserTokenManager.java:1420)
at org.josql.parser.JoSQLParser.jj_scan_token(JoSQLParser.java:3725)
.........
.........
at org.josql.parser.JoSQLParser.Query(JoSQLParser.java:298)
at org.josql.parser.JoSQLParser.parseQuery(JoSQLParser.java:86)
at org.josql.Query.parse(Query.java:2032)
at main.JoSqlTest.main(JoSqlTest.java:12)
Why do you need double quotes?
You can/should use single quotes here...
"Select * from tabName WHERE colName1 = 'type' AND colName2 LIKE '%group/test\"%' ORDER BY colName2 asc"

Resources