Last column data overwritten all the column while inserting - swift3

I having this problem when I inserting data row and the result comes out 'SUCCESS'. But when I print out the table, something like below came out. I have been trying on this for days but couldn't figure out where whet wrong.
Logs:
Successfully inserted row. >> aaa sss ddd fff
Successfully inserted row. >> zzz xxx ccc vvv
Successfully inserted row. >> 9999999 00000000 aaaaaaa bbbbbbbbbbbbb
Successfully inserted row. >> ccccccccccccc ddddddddddd eeeeeeeeeeee fffffffffffffffff
Successfully inserted row. >> gggggggggggg hhhhhhhhhhhh iiiiiiiiiiiii jjjjjjjjjjjjjj
Successfully inserted row. >> kkkkkkkkkkk LLLLLLLLLL mmmmmmmm nnnnnnnnnnnnn
Query Result= id:1 msgID:fff loginID:fff conversationID:fff userID:fff
Query Result= id:2 msgID:vvv loginID:vvv conversationID:vvv userID:vvv
Query Result= id:3 msgID:bbbbbbb loginID:bbbbbbb conversationID:bbbbbbbb userID:bbbbbbbbbbbbb
Query Result= id:4 msgID:ddddddddddd loginID:ddddddddddd conversationID:ddddddddddd userID:fffffffffffffffff
Query Result= id:5 msgID:jjjjjjjjjjjjj loginID:jjjjjjjjjjjj conversationID:jjjjjjjjjjjj userID:jjjjjjjjjjjjjj
Query Result= id:6 msgID:nnnnnnnn loginID:nnnnnnnnnnn conversationID:nnnnnnnnnn userID:nnnnnnnnnnnnn
I'm sure the database connection is fine, but it just came out wrong. I even checked if my parameters are input correctly.
When I call my function:
DB_Handler.add_msgstatus(loginID: "aaa", conversationID: "sss", msgID: "ddd", userID: "fff")
DB_Handler.add_msgstatus(loginID: "zzz", conversationID: "xxx", msgID: "ccc", userID: "vvv")
DB_Handler.add_msgstatus(loginID: "9999999", conversationID: "00000000", msgID: "aaaaaaa", userID: "bbbbbbbbbbbbb")
DB_Handler.add_msgstatus(loginID: "ccccccccccccc", conversationID: "ddddddddddd", msgID: "eeeeeeeeeeee", userID: "fffffffffffffffff")
DB_Handler.add_msgstatus(loginID: "gggggggggggg", conversationID: "hhhhhhhhhhhh", msgID: "iiiiiiiiiiiii", userID: "jjjjjjjjjjjjjj")
DB_Handler.add_msgstatus(loginID: "kkkkkkkkkkk", conversationID: "LLLLLLLLLL", msgID: "mmmmmmmm", userID: "nnnnnnnnnnnnn")
DB_Handler.getAllMsgStatusInfo()
My insert row function:
static func add_msgstatus(loginID: String, conversationID: String, msgID: String, userID: String) {
let queryString = "INSERT INTO msgstatus_tbl (id, msg_id, login_id, conversation_id, user_id) VALUES (null, ?, ?, ?, ?);"
var preparedStmt: OpaquePointer? = nil
if sqlite3_prepare(db, queryString, -1, &preparedStmt, nil) == SQLITE_OK {
sqlite3_bind_text(preparedStmt, 1, msgID, -1, nil)
sqlite3_bind_text(preparedStmt, 2, loginID, -1, nil)
sqlite3_bind_text(preparedStmt, 3, conversationID, -1, nil)
sqlite3_bind_text(preparedStmt, 4, userID, -1, nil)
if sqlite3_step(preparedStmt) == SQLITE_DONE {
print("Successfully inserted row. >> \(loginID) \(conversationID) \(msgID) \(userID)")
} else {
let errorMessage = String.init(cString: sqlite3_errmsg(db))
print("Fail to insert row. \(errorMessage)")
}
sqlite3_finalize(preparedStmt)
} else {
let errorMessage = String.init(cString: sqlite3_errmsg(db))
print("Unable to prepare statement. \(errorMessage)")
}
}
My table:
static func create_msgstatus_tbl() {
let queryString = "CREATE TABLE IF NOT EXISTS msgstatus_tbl (id INTEGER PRIMARY KEY, msg_id VARCHAR(255), login_id VARCHAR(255), conversation_id VARCHAR(255), user_id VARCHAR(255));"
var preparedStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, queryString, -1, &preparedStmt, nil) == SQLITE_OK {
if sqlite3_step(preparedStmt) == SQLITE_DONE {
print("Table (msgstatus_tbl) exists/ created.")
} else {
print("Table (msgstatus_tbl) could not be created.")
}
sqlite3_finalize(preparedStmt)
} else {
let errorMessage = String.init(cString: sqlite3_errmsg(db))
print("Unable to prepare statement. \(errorMessage)")
}
}
My retrieve data function:
static func getAllMsgStatusInfo() {
let queryString = "SELECT * FROM msgstatus_tbl;"
var preparedStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, queryString, -1, &preparedStmt, nil) == SQLITE_OK {
var msgID = ""
var loginID = ""
var conversationID = ""
var userID = ""
var id = ""
while (sqlite3_step(preparedStmt) == SQLITE_ROW) {
id = String(cString: sqlite3_column_text(preparedStmt, 0))
msgID = String(cString: sqlite3_column_text(preparedStmt, 1))
loginID = String(cString: sqlite3_column_text(preparedStmt, 2))
conversationID = String(cString: sqlite3_column_text(preparedStmt, 3))
userID = String(cString: sqlite3_column_text(preparedStmt, 4))
print("Query Result= id:\(id) msgID:\(msgID) loginID:\(loginID) conversationID:\(conversationID) userID:\(userID)")
}
sqlite3_finalize(preparedStmt)
} else {
let errorMessage = String.init(cString: sqlite3_errmsg(db))
print("Unable to prepare statement. \(errorMessage)")
}
}

You need to do one thing.
When you use sqlite3_bind_text(preparedStmt, 1, msgID, -1, nil) then just follow these following steps -:
let msgId = msgID as NSString
sqlite3_bind_text(preparedStmt, 1, msgId.utf8String, -1, nil)
Do these same things for all your next sqlite3_bind_text statement as mentioned in your code.
I also faced same problem like you. And it is working now for me. I hope it will work for you.

Related

How to save a table from Datatables to a database in Django?

I'm using Datatables to display tables in Django on the server side. After searching for a phrase, I have a button ready to save the current table after filtering to Excel. I would like the second button to create a new table in the database and save the same table to it as for Excel.
I don't know how I can send AJAX data to Django and read it in views in such a way that I can query the database.
javascript:
$(document).ready(function () {
function newexportaction(e, dt, button, config) {
var self = this;
var oldStart = dt.settings()[0]._iDisplayStart;
dt.one('preXhr', function (e, s, data) {
data.start = 0;
data.length = 2147483647;
dt.one('preDraw', function (e, settings) {
// Call the original action function
if (button[0].className.indexOf('buttons-excel') >= 0) {
$.fn.dataTable.ext.buttons.excelHtml5.available(dt, config) ?
$.fn.dataTable.ext.buttons.excelHtml5.action.call(self, e, dt, button, config) :
$.fn.dataTable.ext.buttons.excelFlash.action.call(self, e, dt, button, config);
}
dt.one('preXhr', function (e, s, data) {
settings._iDisplayStart = oldStart;
data.start = oldStart;
});
});
});
dt.ajax.reload();
}
$("#tb").DataTable({
"lengthChange": true,
"paging": true,
"searching": true,
"oLanguage": {
"sSearch": "Szukaj:",
},
"language": {
"processing": "Przetwarzanie",
"lengthMenu": "Pokaż _MENU_ elementów",
"info": "Wyświetlono od _START_ do _END_ z _TOTAL_ elementów",
"zeroRecords": "Nie znaleziono pasujących elementów",
"paginate": {
"first": "Pierwsza",
"last": "Ostatnia",
"next": "Kolejna",
"previous": "Poprzednia"
},
"emptyTable": "Brak danych do wyświetlenia",
},
"processing": true,
"serverSide": true,
buttons: [
{
extend: 'excel',
titleAttr: 'Excel',
title: '',
action: newexportaction
},
],
dom: 'B<"clear">lfrtip',
// "destroy": true,
"pageLength": 15,
"ordering": false,
"ajax": {
"url": "paging2/",
"type": "get"
},
});
});
views.py:
def paging2(request):
draw = int (request.GET.get ('draw')) # record the number of operations
start = int (request.GET.get ('start')) # start position
length = int (request.GET.get ('length')) # length of each page
search_key = request.GET.get ('search[value]') # search keyword
order_column = request.GET.get ('order [0] [column]') # sort field index
order_column = request.GET.get ('order [0] [dir]') #Ordering rule: ase / desc
# sql query all data, then do paging, the speed is slow
# if search_key:
# result = query(search_key)
# else:
# result = select_all()
# data = result[start:start+length]
# count = len(result)
# sql for paging, fast
if search_key:
sql_search = "SELECT NAZWA,TEL,NIP,Adres,WWW, EMAIL, Branza, NAZWA_SCRAPERA FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL AND Branza like '%%%s%%'" % search_key
sql_search_len = "SELECT COUNT(*) FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL AND Branza like '%%%s%%'"% search_key
result, count = query(sql_search, sql_search_len)
data = result[start:start + length]
else:
sql = """
SELECT NAZWA,TEL,NIP,Adres,WWW, EMAIL, Branza, NAZWA_SCRAPERA FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL
LIMIT %s OFFSET %s
"""
data = select_by_page(length, start, sql)
# data = select_by_page(start, start + length)
sql_len = "SELECT COUNT(*) FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL"
count = all_count(sql_len)
dic = {
'draw': draw,
'recordsTotal': count,
'recordsFiltered': count,
'data': data,
}
return HttpResponse(json.dumps(dic), content_type='application/json')

DynamoDB Query with sort key and partition key

I am using JS SDK with DynamoDB to fetch data.
I am able to fetch data from my table using simple query with partition key and sort key.
My sort key sk has records -
Year#Batch#Rate
If I pass var sk = "2006#CSE#90"; it returns all of records matching this,
Requirement - How can I get all products with year 2006 , Batch CSE AND Rate =>90
readItem_pbro(){
console.log("inside pbro");
var table2 = "pbro";
var pk = "1";
var sk = "2006#CSE#90";
var params2 = {
TableName: table2,
Key:{
"pk": pk,
"sk": sk
}
};
Edit 1 :: Created a different column for score/rate as score. It is numeric.
Now my query in JS is -
but I am getting error - ValidationException: The provided key element does not match the schema
readItem_score_filter(){
console.log("inside pbro");
var table2 = "pbro";
var pk = "1"; // string
var sk = "2006#CSE"; // string
var score = 90; //number
var params2 = {
TableName: table2,
Key:{
"pk": pk,
"sk": sk,
FilterExpression:'score >=:score',
}
};
what is wrong in my FilterExpression.
Edit 2 :: Added Key condition Expression but issue still remains the same
Error: ValidationException: The provided key element does not match the schema
Here is my complete function now:
readItem_score_filter(){
console.log("inside pbro");
var table2 = "pbro";
var pk = "1"; //string
var sk = "2006#CSE"; // string
var score = 90; //number
var params2 = {
TableName: table2,
Key:{
"pk": pk,
"sk": sk,
"score": score,
KeyConditionExpression: 'pk = :pk AND sk=:sk',
FilterExpression: "score >=:score",
}
};
this.user.docClient.get(params2, function(err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
}
Screenshot of table attached incase you need to see::
If "2006#CSE#90" this is the value of sort key column then you cant do anything at Dynamodb level..
comparings like this can be done through regular expressions but DynamoDB doesn't support Regular Expressions.
you simply need to get results and then seperate these values and compare ..
Updated :- use different column for score.
And use Filter Expression to get records having rate more than 90.
I dont know python , but still am trying here
var params2 = {
TableName: "pbro",
KeyConditionExpression: "pk = :pk AND sk =:sk",
FilterExpression: "score >= :score"
};

Unresolved Identifier error within #IBAction func

I am writing a basic iOS app to test my Swift knowledge and keep on practicing. In my app the user types a name for a baby, then turns a switch either on or off to set the gender/sex and also change the system color.
After that, the name is used to fill in a UITextView, named "firstWords", in the following block of code:
// Save name entered into text field
#IBAction func saveSettings(_ sender: UIButton) {
nameLabel.text = nameTextField.text
if nameTextField.text == "" {
showMessage()
nameLabel.text = "Baby Name"
}
nameTextField.resignFirstResponder()
let nameHolder: String! = nameLabel.text
if boyGirlSwitch.isOn {
let sex = ("boy", "his", "he", "Boy", "His", "He")
} else {
let sex = ("girl", "her", "she", "Girl", "Her", "She")
}
firstWords.text = "Wow, " + nameHolder + " has so much to look forward to!" + (sex.5) + " will do so many great things!"
}
I keep getting an error at the tuple (sex.5) inside firstWords that says: "Use of unresolved identifier 'sex'"
As I understand it, the constant sex is declared within the if statement and the compiler does go through it either way, so it does get identified and declared.
QUESTION: Why am I getting the error?
Thanks in advance! Here's a screenshot of my code as well:
Screenshot of block of code as described above, including the compiler/build-error
This is a scope issue. sex is only available within the else clause.
You can fix it like this
// Save name entered into text field
#IBAction func saveSettings(_ sender: UIButton) {
nameLabel.text = nameTextField.text
if nameTextField.text == "" {
showMessage()
nameLabel.text = "Baby Name"
}
nameTextField.resignFirstResponder()
let nameHolder: String! = nameLabel.text
var sex : (String, String, String, String, String, String)
if boyGirlSwitch.isOn {
sex = ("boy", "his", "he", "Boy", "His", "He")
} else {
sex = ("girl", "her", "she", "Girl", "Her", "She")
}
firstWords.text = "Wow, " + nameHolder + " has so much to look forward to!" + (sex.5) + " will do so many great things!"
}
this way sex is defined within the scope of the whole IBAction and will be available in the end.
you could also skip one condition if you pre-declare it with a default:
// Save name entered into text field
#IBAction func saveSettings(_ sender: UIButton) {
nameLabel.text = nameTextField.text
if nameTextField.text == "" {
showMessage()
nameLabel.text = "Baby Name"
}
nameTextField.resignFirstResponder()
let nameHolder: String! = nameLabel.text
var sex = ("girl", "her", "she", "Girl", "Her", "She")
if boyGirlSwitch.isOn {
sex = ("boy", "his", "he", "Boy", "His", "He")
}
firstWords.text = "Wow, " + nameHolder + " has so much to look forward to!" + (sex.5) + " will do so many great things!"
}
There is actually a nice article about variable scope on Wikipedia: https://en.wikipedia.org/wiki/Scope_(computer_science)

how we find and replace array dictionary value in swift 3

My array has this dictionary I want to find and replace where dictionary h
attendance = "" and attendance = "A" and replace with attendance = "P"
I am using this:
checkedArray = [[String : AnyObject]]()
let index = find(checkedArray) { $0["attendance"] == "P" }
if let index = index {
checkedArray[index] = newDictionary
}
// Do any additional setup after loading the view.
}
func find<C: CollectionType>(collection: C, predicate: (C.Generator.Element) -> Bool) -> C.Index? {
for index in collection.startIndex ..< collection.endIndex {
if predicate(collection[index]) {
return index
}
}
return nil
}
[
{"studentID":"12","name":"panky","roll":"","attendance":"P"},
{"studentID":"14","name":"a","roll":"","attendance":""},
{"studentID":"4","name":"akshay","roll":"1","attendance":"E"},
{"studentID":"6","name":"anki","roll":"11","attendance":"P"},
{"studentID":"1","name":"mohit","roll":"2","attendance":"M"},
{"studentID":"5","name":"yogi","roll":"22","attendance":"L"},
{"studentID":"3","name":"Neha","roll":"3","attendance":"A"}
]
let dic: [[String : Any]] = [
["studentID":"12","name":"panky","roll":"","attendance":"P"],
["studentID":"14","name":"a","roll":"","attendance":""],
["studentID":"4","name":"akshay","roll":"1","attendance":"E"],
["studentID":"6","name":"anki","roll":"11","attendance":"P"],
["studentID":"1","name":"mohit","roll":"2","attendance":"M"],
["studentID":"5","name":"yogi","roll":"22","attendance":"L"],
["studentID":"3","name":"Neha","roll":"3","attendance":"A"]
]
let result : [Any] = dic.map { dictionary in
var dict = dictionary
if let attendance = dict["attendance"] as? String, attendance == "" || attendance == "A" {
dict["attendance"] = "P"
}
return dict
}

SWIFT 3 Predicate for NSArray not working properly with numbers

I am learning to use predicates for filtering. I found a tutorial, but one aspect is not working for me in Swift 3. Here is some specific code:
let ageIs33Predicate01 = NSPredicate(format: "age = 33") //THIS WORKS
let ageIs33Predicate02 = NSPredicate(format: "%K = 33", "age") //THIS WORKS
let ageIs33Predicate03 = NSPredicate(format: "%K = %#", "age","33") //THIS DOESN'T WORK
let ageIs33Predicate04 = NSPredicate(format: "age = %#","33") //THIS DOESN'T WORK
All 4 compile, but the last 2 produce no results even though I have a case where age = 33. Here is the test complete test code from the tutorial:
import Foundation
class Person: NSObject {
let firstName: String
let lastName: String
let age: Int
init(firstName: String, lastName: String, age: Int) {
self.firstName = firstName
self.lastName = lastName
self.age = age
}
override var description: String {
return "\(firstName) \(lastName)"
}
}
let alice = Person(firstName: "Alice", lastName: "Smith", age: 24)
let bob = Person(firstName: "Bob", lastName: "Jones", age: 27)
let charlie = Person(firstName: "Charlie", lastName: "Smith", age: 33)
let quentin = Person(firstName: "Quentin", lastName: "Alberts", age: 31)
let people = [alice, bob, charlie, quentin]
let ageIs33Predicate01 = NSPredicate(format: "age = 33")
let ageIs33Predicate02 = NSPredicate(format: "%K = 33", "age")
let ageIs33Predicate03 = NSPredicate(format: "%K = %#", "age","33")
let ageIs33Predicate04 = NSPredicate(format: "age = %#","33")
(people as NSArray).filtered(using: ageIs33Predicate01)
// ["Charlie Smith"]
(people as NSArray).filtered(using: ageIs33Predicate02)
// ["Charlie Smith"]
(people as NSArray).filtered(using: ageIs33Predicate03)
// []
(people as NSArray).filtered(using: ageIs33Predicate04)
// []
What am I doing wrong? Thanks.
Why would the last two work? You are passing a String in for an Int property. You need to pass in an Int to compare against the Int property.
Change the last two to:
let ageIs33Predicate03 = NSPredicate(format: "%K = %d", "age", 33)
let ageIs33Predicate04 = NSPredicate(format: "age = %d", 33)
Note the change in the format specifier from %# to %d.