I'm currently working on UWP project and I use sqlite database.In this project I want to update field in sqlite table(classroomteam).When I entered value with apostrophe(') It gives error saying "SQLite.SQLiteException: 'near "s": syntax error'"
This is the code that I used to save updated data to the table
public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
{
IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
ClassroomTeam classroomTeam = new ClassroomTeam()
{
TeamName = classroomTeamItem.TeamName,
Id = classroomTeamItem.Id,
};
String teamName = classroomTeamItem.TeamName;
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
//Task<int> a = conn.UpdateAsync(configInfo);
await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '" + classroomTeamItem.TeamName + "' WHERE Id = '" + classroomTeam.Id + "'");
await conn.CloseAsync();
IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
}
I tried this to solve my issue and what I did is applying new String[] {classroomTeamItem.TeamName } in the query.Then I didn't get any error but the value is stored as System.String[] not the value I entered in sqlite table.The code I tried as follows.
public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
{
IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
ClassroomTeam classroomTeam = new ClassroomTeam()
{
TeamName = classroomTeamItem.TeamName,
Id = classroomTeamItem.Id,
};
String teamName = classroomTeamItem.TeamName;
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
//Task<int> a = conn.UpdateAsync(configInfo);
await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '" + new String[] { classroomTeam.TeamName } + "' WHERE Id = '" + classroomTeam.Id + "'");
await conn.CloseAsync();
IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
}
I would appreciate if anyone can help me to resolve this issue.
The sql string about how to update field is:
string SQL_UPDATE = "UPDATE " + TABLE_NAME + " SET Value = ? WHERE Key = ?";
So you could try to change your update string to
await db.ExecuteAsync("UPDATE classroomteam SET TeamName = " + classroomTeamItem.TeamName + " WHERE Id = " + classroomTeam.Id);
Or you can query for the specific data is most straightforwardly done using the Table method and then update your field. For example:
private async void update(ClassroomTeamItem classroomTeamItem)
{
var query = db.Table<ClassroomTeam>().Where(s => s.Id==classroomTeam.Id);
var result = await query.ToListAsync();
foreach (var s in result)
{
s.TeamName = classroomTeamItem.TeamName;
await db.UpdateAsync(s);
}
}
Related
I have following class that connects to database but when I trye to call the method that saves data I get error "Database is locked". Could some one please help me to find the problem?
class Data
{
private SQLiteConnection con;
private void ConnectoDB()
{
String PathDB = Directory.GetCurrentDirectory();
PathDB += "\\SQLiteDB_MEDFit.db";
string cs = #"URI=file:" + PathDB;
string stm = "SELECT SQLITE_VERSION()";
con = new SQLiteConnection(cs);
con.Open();
var cmd = new SQLiteCommand(stm, con);
string version = cmd.ExecuteScalar().ToString();
}
public Boolean SaveToDatabase(string name, string number)
{
bool result = false;
try
{
ConnectoDB();
con.Execute("insert into People(name, number) values ('" + name+ "', '" + number+ "')");
con.Close();
result = true;
MessageBox.Show("Saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
}
The code that calls the "SaveToDatabase()"
string name = textBox1.Text();
string number = textBox2.Text();
Data connect = new Data();
connect.SavetoDB(name, number);
I have a table displaying vacation requests from employees. Right now I'm displaying requests from all years in that table with the "onAttach" event. I want to implement a dropdown with a binding to the "year" column in my external sql data. so whenever I select a year out of that dropdown, I want the table to update only showing requests from that specific year in the table. How do I implement it?
the onAttach function loadHolidayTable() of the table leads to this client function
function loadHolidayTable() {
app.datasources.HolidayModel.load({
failure: function (error) {
displayTimedSnackbar('Unable to load holidays table: ' + error);
}
});
}
My Server Script in the datasource "HolidayModel"
return calculateHolidayModel(query);
leads to this server function:
function calculateHolidayModel(query) {
var queryStr = '';
var currentYear = null; --> to be replaced by dropdown value
if (currentYear === null || currentYear == 'undefined') {
queryStr = 'SELECT * FROM Holidays WHERE employeeID = ' + "'" + empID + "'";
}
else {
queryStr = 'SELECT * FROM Holidays WHERE employeeID = ' + "'" + empID + "'" + ' AND year = ' + "'" + currentYear + "'";
}
console.log(queryStr);
//var dayRecords = [];
var holidayRecords = [];
var connection = getJDBCConnection_();
var statement = connection.prepareStatement(queryStr);
try {
var results = statement.executeQuery();
while(results.next()) {
var holidayRecord = app.models.HolidayModel.newRecord();
holidayRecord.ID = results.getInt(2);
holidayRecord.From = new Date(results.getString(3));
holidayRecord.To = new Date(results.getString(4));
holidayRecord.Status = results.getString(5);
holidayRecords.push(holidayRecord);
console.log(results.getInt(2));
}
results.close();
statement.close();
} catch (err) {
console.log(err);
}
return holidayRecords;
}
currentYear should be replaced by the value from the dropdown.
any suggestions are welcome!
I have a sqlite db file. I am using DB Browser for Sqlite as the client. I went in and ran delete from command on most of my tables. Thereafter I tried to export using the option Database to SQL file I notice all my data is appearing in it. What I wondering is that why the data have not been deleted? I know the sqlite file size will not shrink.
Below is snippet of my codes.
string str = #"Data Source=" + userFilePath + "\\mysqlite.sqlite3";
using (SQLiteConnection con = new SQLiteConnection(str))
{
con.Open();
SQLiteTransaction trans = con.BeginTransaction();
try
{
String cmdSelect1 = "Select * from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
int fiscalPeriod = Convert.ToInt32(monthNumber);
int financialYear = Convert.ToInt32(itemvalueyear);
using (SQLiteCommand cmd1 = new SQLiteCommand(cmdSelect1, con, trans))
{
SQLiteDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Records Already Exist ? Are you confirm replace it?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
String deleteTable = "Delete from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
using (SQLiteCommand cmdDeleteTb1 = new SQLiteCommand(deleteTable, con, trans))
{
cmdDeleteTb1.ExecuteNonQuery();
cmdDeleteTb1.Dispose();
}
foreach (object line in linesC)
{
if (line.GetType() == typeof(TypeC))
{
String cmdText2 = "INSERT INTO table1(tbID,companyID,month,year) VALUES(#tbID,#companyID,#month,#year)";
using (SQLiteCommand cmd = new SQLiteCommand(cmdText2, con, trans))
{
cmd.Parameters.AddWithValue("#tbID", tbID);
cmd.Parameters.AddWithValue("#companyID", companyID);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#year", year);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
}
}
}
}
}
dr1.Close();
cmd1.Dispose();
}
trans.Commit();
MessageBox.Show("Successfully Inserted Into Database");
}
catch (Exception ex)
{
MessageBox.Show("Rollback " + ex.ToString());
trans.Rollback();
}
con.Close();
con.Dispose();
GC.Collect();
Ok:
It appears you are beginning two transactions. You begin your loop inserts after you begin your delete.
Commit your Delete transaction and then later commit your inserts.
This is than committing after beginning both transactions.
I'm creating an asp.net mvc4 application, that can write data into database tables from excel sheets(using sqlbulkcopy column mapping). when we select excel sheet and submit, it is writing data into database.
Now I want to set file uploaded time as timestamp for each data rows when it write data into database table.
Code:
namespace AFFEMS2_HEC.Controllers
{
public class ExcelController : Controller
{
//
// GET: /Excel/
public ActionResult Index()
{
return View();
}
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(HttpPostedFileBase FileUpload1)
{
//Upload and save the file
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string excelPath = Path.Combine(HttpContext.Server.MapPath("~/Content/"), Path.GetFileName(FileUpload1.FileName));
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
string sheet2 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[1]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[4] {
new DataColumn("Id", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("Email",typeof(string)),
new DataColumn("Mobile", typeof(int)) });
string query = "SELECT s1.Id, " +
"s1.Name, " +
"s1.Mobile, " +
"s2.Email " +
"FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)";
using (OleDbDataAdapter oda = new OleDbDataAdapter(query, excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con,
SqlBulkCopyOptions.CheckConstraints|
SqlBulkCopyOptions.FireTriggers|
SqlBulkCopyOptions.KeepNulls|
SqlBulkCopyOptions.TableLock|
SqlBulkCopyOptions.UseInternalTransaction,
null))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "User1";
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
con.Open();
try
{
// Write from the source to the destination
sqlBulkCopy.WriteToServer(dtExcelData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
return View();
}
}
}
Just create another column as "TimeStamp_Inserted" but it type should be datetime or
nvarchar
and try to replace following code snippet
string query = "SELECT s1.Id, " +
"s1.Name, " +
"s1.Mobile, " +
"s2.Email " +
"'"+DateTime.Now.ToString() +"'"+" as TimeStamp_Inserted"+
"FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)";
sqlbulkcopy column mapping try to change like this
sqlBulkCopy.DestinationTableName = "User1";
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
sqlBulkCopy.ColumnMappings.Add("TimeStamp_Inserted", "TimeStamp");
con.Open();
just try it
I'm getting results from my rawQuery that duplicate and follow an OR logic as opposed to an AND logic i.e. I will get all the entries that contain "tuxedo" as well as all the entries that contain "hotel" when I only want the ones that contain both.
This is my method:
public ArrayList<Integer> getAdvancedResultIDList(String[] search)
{
ArrayList<String> queryList = new ArrayList<String>();
ArrayList<Integer> resultsList = new ArrayList<Integer>();
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
this.mDB = GamesList.mDBHelper.getDatabase();
Cursor searchCursor = null;
try
{
//TODO:
// for each string in the search array search the whole of searchable table. Check that the results are only of the values that
// contain all the search strings, and add the id of that row to the results ArrayList
for(int i = 0; i < search.length; i++)
{
String query;
String s = '"' + search[i] + '"';
query = "SELECT " + KEY_ID + " FROM "+ SEARCHABLE_TABLE + " WHERE " + SEARCHABLE_TABLE + " MATCH " + s;
queryList.add(query);
}
String[] queryArray = queryList.toArray(new String[queryList.size()]);
String unionQuery = builder.buildUnionQuery(queryArray, KEY_ID + " ASC", null);
searchCursor = this.mDB.rawQuery(unionQuery, null);
int colId = searchCursor.getColumnIndex(KEY_ID);
String resultID;
for(searchCursor.moveToFirst(); !searchCursor.isAfterLast();searchCursor.moveToNext())
{
resultID = searchCursor.getString(colId);
Integer Id = Integer.parseInt(searchCursor.getString(colId));
resultsList.add(Id);
}
searchCursor.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
this.mDB.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
return resultsList;
}
Thanks in advance and Happy New Year!
The documentation explains how to use multiple search terms:
SELECT id FROM searchTable WHERE searchTable MATCH 'tuxedo hotel'