Delete from command not working in sqlite? - sqlite

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.

Related

How to managed two sql queries in ASP.Net (Visual Studio 2010)

So what I'm trying to do is once I click a button. I want one sql query to insert values to the "Return_Process" Table and another sql query to delete data from the matching loan ID in another table, which is "Loan_Process".
This is the code I have written but its not deleting anything, its inserting the values to the return process but not deleting it from the loan process.
//Global variable declaration
string path;
string sql;
string sql2;
//create a method for database connection
public void connection()
{
//connection string
path = #"Data Source=NATHAN-PC\SQLEXPRESS;Initial Catalog=ASP;Integrated Security=True";
}
protected void Button1_Click(object sender, EventArgs e)
{
{
connection();
SqlConnection con = new SqlConnection(path);
con.Open();
//try
{
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID) VALUES ('" + txtRID.Text + "','" + txtfine.Text + "','" + TextBox1.Text + "','" + txtLID.Text + "')";
sql2 = "Delete FROM Loan_Process WHERE Loan_ID='"+txtLID+"'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
//lblerrormsg.Visible = true;
//lblerrormsg.Text = "Success";
con.Close();
//GridView1.DataBind();
}
//catch (SqlException)
//{
// //lblerrormsg.Visible = true;
// //lblerrormsg.Text = "Invalid";
//}
con.Close();
//GridView1.DataBind();
}
}
}
}
I'm pretty bad at ASP.net, so if someone could tell me what to do to execute both queries at the same time, would greatly appreciate it.
Do something like this:
//your code
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID)"
+ " VALUES (#rid, #fine, #retDate, #lid); " //note ; inside
+ "Delete FROM Loan_Process WHERE Loan_ID=#lid;";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#rid", SqlDbType.Int).Value = Int.Parse(txtRID.Text);
//similar for 3 remaining parameters. Just set correct SqlDbType
con.Open();
cmd.ExecuteNonQuery();
con.Close();

set a constant(same) time stamp for multiple data base rows

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

How to update sql database table info with excel file using file uploaded

I am trying to update the files in the table that I have created. I am using file uploader to insert my Excel file and upload it to the database. But currently my code creates a new database table each time a file is uploaded, which I don't want it to do. I want to just update/replace the whole file in database table. How do I do this?
This is my code:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["nConnectionString2"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
int maxLength = 0;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
if (maxLength > 0)
{
sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
}
else
{
sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
}
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadExcelFile") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'MyCSVFolder'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadExcelFile") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
// load the data from CSV to DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label1.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
Label1.Text = "File is empty.";
}
}
else
{
Label1.Text = "Unable to recognize file.";
}
}
}
The code that creates the tables should give an error when you run it if the tables already exists as you never drop them.
That said, one solution might be to add a check to see if the table already exists in the code that creates a new table; it should be something like:
IF OBJECT_ID('TABLE', 'U') IS NULLwhere TABLEit the name of the table that you want to add, so the code might look like:
sb.AppendFormat(string.Format("IF OBJECT_ID({0}, 'U') IS NULL CREATE TABLE {0} (", tableName));
Another, possibly better, option would be to run a query to check if the table exists before you run the CreateDatabaseTable(dtCSV, fileName);statement. You can do the check by executing something like IF OBJECT_ID('tableName', 'U') IS NULL SELECT 1 ELSE SELECT 0 (this would return 1 if the table doesn't exist), and then conditionally execute the CreateDatabaseTablestatement.

what is wrong with this C# duplicate row code?

I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct

Insert ADO.Net DataTable into an SQL table

The current solution i implemented is awful!
I use a for... loop for inserting records from an ADO.NET data-table into an SQL table.
I would like to insert at once the data-table into the SQL table, without iterating...
Is that possible, or am i asking too much?
You can pass the entire DataTable as a single Table Valued Parameter and insert the entire TVP at once. The following is the example from Table-Valued Parameters in SQL Server 2008 (ADO.NET):
// Assumes connection is an open SqlConnection.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories = CategoriesDataTable.GetChanges(
DataRowState.Added);
// Define the INSERT-SELECT statement.
string sqlInsert =
"INSERT INTO dbo.Categories (CategoryID, CategoryName)"
+ " SELECT nc.CategoryID, nc.CategoryName"
+ " FROM #tvpNewCategories AS nc;"
// Configure the command and parameter.
SqlCommand insertCommand = new SqlCommand(
sqlInsert, connection);
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
"#tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.CategoryTableType";
// Execute the command.
insertCommand.ExecuteNonQuery();
}
TVP are only available in SQL 2008.
I think you are looking for SQLBulkCopy.
SqlBulkCopy is the simplest solution.
using (SqlConnection dbConn = new SqlConnection(connectionString))
{
dbConn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dbConn))
{
bulkCopy.DestinationTableName =
"dbo.MyTable";
try
{
bulkCopy.WriteToServer(myDataTable, DataRowState.Added);
}
catch (Exception ex)
{
myLogger.Error("Fail to upload session data. ", ex);
}
}
}
You can create SqlBulkCopyColumnMapping if the columns in your DataTable don't match your database table.
You can also try the following method.
private void button1_Click(object sender, EventArgs e)
{
tabevent();
DataSet ds = new DataSet();
DataTable table = new DataTable("DataFromDGV");
ds.Tables.Add(table);
foreach (DataGridViewColumn col in dataGridView1.Columns)
table.Columns.Add(col.HeaderText, typeof(string));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
table.Rows.Add(row);
foreach (DataGridViewCell cell in row.Cells)
{
table.Rows[row.Index][cell.ColumnIndex] = cell.Value;
}
}
// DataTable ds1changes = ds1.Tables[0].GetChanges();
if (table != null)
{
SqlConnection dbConn = new SqlConnection(#"Data Source=wsswe;Initial Catalog=vb;User ID=sa;Password=12345");
SqlCommand dbCommand = new SqlCommand();
dbCommand.Connection = dbConn;
foreach (DataRow row in table.Rows)
{
if (row["quantity"] != null && row["amount"]!=null && row["itemname"]!=null)
{
if (row["amount"].ToString() != string.Empty)
{
dbCommand.CommandText =
"INSERT INTO Bill" +
"(Itemname,Participants,rate,Quantity,Amount)" +
"SELECT '" + Convert.ToString(row["itemname"]) + "' AS Itemname,'" + Convert.ToString(row["Partcipants"]) + "' AS Participants,'" + Convert.ToInt32(row["rate"]) + "' AS rate,'" +
Convert.ToInt32(row["quantity"]) + "' AS Quantity,'" + Convert.ToInt32(row["amount"]) + "' AS Amount";
dbCommand.Connection.Open();
dbCommand.ExecuteNonQuery();
if (dbCommand.Connection.State != ConnectionState.Closed)
{
dbCommand.Connection.Close();
}
MessageBox.Show("inserted");
}
}
}
}
}

Resources