C# SQLite database locked - c#

I've tried all the solutions I could find to this problem, but for some reason I still get an exception stating the database I'm using is locked.
My code is as follows:
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
using (SQLiteConnection OriginatorDBConnection = new SQLiteConnection(connectionString))
{
string originatorName, originatorOrganisation, originatorAddress, originatorCellNumber, originatorTelNumber, originatorEmail;
originatorName = originatorNameTextBox.Text;
originatorOrganisation = originatorOrganisationTextBox.Text;
originatorAddress = originatorAddressRichTextBox.Text;
originatorCellNumber = originatorCellTextBox.Text;
originatorTelNumber = originatorTelTextBox.Text;
originatorEmail = originatorEmailTextBox.Text;
OriginatorDBConnection.Open();
string originatorINSERT = "INSERT INTO Originator (Name, Organisation, Address, CellphoneNumber, TelephoneNumber, Email) VALUES ('" + originatorName + "', '" + originatorOrganisation + "', '" + originatorAddress + "', '" + originatorCellNumber + "', '" + originatorTelNumber + "', '" + originatorEmail + "');";
using (SQLiteCommand originatorCommand = new SQLiteCommand(originatorINSERT, OriginatorDBConnection))
{
originatorCommand.ExecuteNonQuery();
}
OriginatorDBConnection.Close();
}
The closest solution on here that I could find to the problem was here: SQLite Database Locked exception
It didn't seem to work on my problem, however.
What am I doing wrong?
I have an additional function wherein I use the connection:
public AdminForm()
{
//Initialise AdminForm components.
InitializeComponent();
//Establish and open connection to ObservationDB.
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
ObservationDBConnection = new SQLiteConnection(connectionString);
ObservationDBConnection.Open();
//Query database to find all originators
string originatorSELECT = "SELECT * FROM Originator;";
string ECPNumberSELECT = "SELECT * FROM ECP";
SQLiteCommand command = new SQLiteCommand(originatorSELECT, ObservationDBConnection);
SQLiteDataReader reader = command.ExecuteReader();
SQLiteCommand command2 = new SQLiteCommand(ECPNumberSELECT, ObservationDBConnection);
SQLiteDataReader reader2 = command2.ExecuteReader();
//Populate OriginatorName combobox with names of existing originators.
List<string> originatorNames = new List<string>();
while (reader.Read())
{
originatorNames.Add(Convert.ToString(reader["Name"]));
}
OriginatorNameComboBox.DataSource = originatorNames;
//Populate ECP combobox with numbers of existing ECP.
List<string> ECPNumbers = new List<string>();
while (reader2.Read())
{
ECPNumbers.Add(Convert.ToString(reader2["Number"]));
}
ECPNumComboBox.DataSource = ECPNumbers;
//Populate TC Decision combobox with options.
List<string> TCDecision = new List<string>();
TCDecision.Add("Rework");
TCDecision.Add("Reject");
TCDecision.Add("Approve");
TCDecisionComboBox.DataSource = TCDecision;
ObservationDBConnection.Close();
}
And here:
private void SaveButton_Click(object sender, EventArgs e)
{
ObservationDBConnection.Open();
...
string ImpactTypeINSERT = "INSERT INTO ImpactType (ImpactType, Description) VALUES ('" + impactType + "', '" + impactDescription + "');";
SQLiteCommand ImpactTypeCommand = new SQLiteCommand(ImpactTypeINSERT, ObservationDBConnection);
//SQLiteDataReader ImpactTypeReader = ImpactTypeCommand.ExecuteReader();
ImpactTypeCommand.ExecuteNonQuery();
...
string TCDecisionINSERT = "INSERT INTO TCDecision (Decision, Description) VALUES ('" + TechnicalCommitteeDecision + "', '" + TechnicalCommitteeDescription + "');";
SQLiteCommand TCDecisionCommand = new SQLiteCommand(TCDecisionINSERT, ObservationDBConnection);
SQLiteDataReader TCDecisionReader = ImpactTypeCommand.ExecuteReader();
TCDecisionCommand.ExecuteNonQuery();
...
string OperationalDecisionINSERT = "INSERT INTO OperationalDecision (Decision, Description) VALUES ('" + operationalDecision + "', '" + operationalDescription + "');";
SQLiteCommand OperationalDecisionCommand = new SQLiteCommand(OperationalDecisionINSERT, ObservationDBConnection);
//SQLiteDataReader OperationalDecisionReader = OperationalDecisionCommand.ExecuteReader();
OperationalDecisionCommand.ExecuteNonQuery();
...
...
string OriginatorIDSELECT = "SELECT * FROM Originator WHERE Name='" + OriginatorNameComboBox.Text + "';";
SQLiteCommand OriginatorIDCommand = new SQLiteCommand(OriginatorIDSELECT, ObservationDBConnection);
SQLiteDataReader OriginatorIDReader = OriginatorIDCommand.ExecuteReader();
originatorIDOBS = OriginatorIDReader.GetOrdinal("ID");
//ImpactType
string impactTypeSELECT = "SELECT * FROM ImpactType WHERE ImpactType='" + impactType + "';";
SQLiteCommand impactTypeOBSCommand = new SQLiteCommand(impactTypeSELECT, ObservationDBConnection);
SQLiteDataReader impactTypeOBSReader = impactTypeOBSCommand.ExecuteReader();
impactTypeOBS = impactTypeOBSReader.GetOrdinal("ID");
string operationalDecisionOBSSELECT = "SELECT * FROM OperationalDecision WHERE Decision='" + operationalDecision + "';";
SQLiteCommand operationalDecisionOBSCommand = new SQLiteCommand(operationalDecisionOBSSELECT, ObservationDBConnection);
SQLiteDataReader operationalDecisionOBSReader = operationalDecisionOBSCommand.ExecuteReader();
operationalDecisionOBS = operationalDecisionOBSReader.GetOrdinal("ID");
...
string ECPOBSSELECT = "SELECT * FROM ECP WHERE Number='" + ECPNumComboBox.Text + "';";
SQLiteCommand ECPCommand = new SQLiteCommand(ECPOBSSELECT, ObservationDBConnection);
SQLiteDataReader ECPReader = ECPCommand.ExecuteReader();
ECPOBS = ECPReader.GetOrdinal("ID");
string CNISObservationINSERT = "INSERT INTO CNISObservation (Title, ReceiveDate, TableDate, OriginatorID, OriginatorReference, OriginatorDate, ObservationNumber, RevisionNumber, Description, Status, ImpactDescription, ImpactType, OperationalRequirementDescription, OperationalImpact, OperationalDecision, ProposedAction, TCDecision, ECP, SolutionOperationalImpact, TechnicalSolutionImpact) VALUES ('" +
titleOBS + "','"
+ receiveDateOBS + "','"
+ tableDateOBS + "','"
+ originatorIDOBS + ",'"
+ originatorReferenceOBS +"','"
+ originatorDateOBS + "','"
+ observationNumberOBS + "',"
+ revisionNumberOBS + ",'"
+ descriptionOBS + "',"
+ statusOBS + ",'"
+ impactDescriptionOBS + "',"
+ impactTypeOBS + ",'"
+ operationalRequirementDescriptionOBS + "','"
+ operationalImpactOBS + "',"
+ operationalDecisionOBS + ",'"
+ TCDecisionOBS + ","
+ ECPOBS + ",'"
+ solutionOperationalImpactOBS + "','"
+ technicalSolutionImpactOBS + "');";
...
string obsOBSSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationIDCommand = new SQLiteCommand(obsOBSSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationIDReader = CNISObservationIDCommand.ExecuteReader();
observationID = CNISObservationIDReader.GetOrdinal("ID");
...
foreach (var capabilityID in capabilitiesSelected)
{
string ObservationOperationalCapabilitiesINSERT = "INSERT INTO ObservationOperationalCapabilities (CapabilityID, ObservationID) VALUES (" + capabilityID + "," + observationID + ");";
SQLiteCommand ObservationOperationalCapabilitiesCommand = new SQLiteCommand(ObservationOperationalCapabilitiesINSERT, ObservationDBConnection);
// SQLiteDataReader ObservationOperationalCapabilitiesReader = ObservationOperationalCapabilitiesCommand.ExecuteReader();
ObservationOperationalCapabilitiesCommand.ExecuteNonQuery();
}
...
string CNISObservationIDSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationCommand = new SQLiteCommand(CNISObservationIDSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationReader = CNISObservationCommand.ExecuteReader();
CNISObservationID = CNISObservationReader.GetOrdinal("ID");
string CNISReleaseINSERT = "INSERT INTO CNISSection VALUES (" + CNISObservationID + "," + CNISRelease + "," + chapter + ",'" + paragraph + "','" + section + "','" + page +"');";
SQLiteCommand CNISReleaseCommand = new SQLiteCommand(CNISReleaseINSERT, ObservationDBConnection);
//SQLiteDataReader CNISReleaseReader = CNISReleaseCommand.ExecuteReader();
CNISReleaseCommand.ExecuteNonQuery();
ObservationDBConnection.Close();
}

I know I'm a lot late to the game, but it looks like you're not closing you reader variables in AdminForm() constructor. Consider wrapping the DataReaders in a using().

Wrapping around Command and Reader did work for me:
using (SqliteCommand cmd = new SqliteCommand(sQuery, m_Conn))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
ret_type = reader.GetInt32(0);
}
}
}

Please be aware to click on Write changes on SQLite browser if it is running and there are any unsaved changes!
In my case it was very stupid of me, I was making changes in SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post request worked as expected.
According to #Rohan Shenoy in this topic: SQLite Database Locked exception

Related

Trying to read data from sql database and show on textboxes - Visual C# (syntax error)

edit: I'm aware of SQL Injection.
First of all, I know my coding methods are terrible but thats what I can for now, extremely beginner on c#.
I'm trying to read data from SQL server and show them on Textboxes.
User going to write (and choose from cmbbox) some data on;
cmbIl.Text, cmbIlce.Text, cmbMahalle.Text, txtAda.Text, txtPafta.Text
and press the button for search.
If that data correspond to the values in sql database (true), some other data will be taken and shown at
txtTapuKodu.Text, txtPafta.Text, txtTapuAlani.Text, txtNitelik.Text,
rtxtImarDurumu.Text
But the code below gives that error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
private void btnSorgula_Click(object sender, EventArgs e)
{
string source = #"Data Source=YAGIZ-PC;Initial Catalog=imar_sorgu;Integrated Security=True";
SqlConnection con = new SqlConnection(source);
con.Open();
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "', ilce = '" + cmbIlce.Text + "', mahalle = '" + cmbMahalle.Text + "', ada = '" + txtAda.Text + "', parsel = '" + txtParsel.Text + "'";
/* string sqlSelectQuery2 = "SELECT * FROM tablo_arsa WHERE ilce ='" + cmbIlce.Text + "'";
string sqlSelectQuery3 = "SELECT * FROM tablo_arsa WHERE mahalle ='" + cmbMahalle.Text + "'";
string sqlSelectQuery4 = "SELECT * FROM tablo_arsa WHERE ada = " + txtAda.Text;
string sqlSelectQuery5 = "SELECT * FROM tablo_arsa WHERE parsel = " + txtParsel.Text; */
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtTapuKodu.Text = (dr["tapu_kodu"].ToString());
txtPafta.Text = (dr["pafta"].ToString());
txtTapuAlani.Text = (dr["tapu_alani"].ToString());
txtNitelik.Text = (dr["nitelik"].ToString());
rtxtImarDurumu.Text = (dr["imar_durumu"].ToString());
MessageBox.Show("İstek başarıyla okundu.");
}
else
{
MessageBox.Show("Okuma başarısız.");
}
con.Close();
}
The problem is that your where clause contains commas between the predicates. use AND instead.
change:
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "', ilce = '" + cmbIlce.Text + "', mahalle = '" + cmbMahalle.Text + "', ada = '" + txtAda.Text + "', parsel = '" + txtParsel.Text + "'";
to:
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "' AND ilce = '" + cmbIlce.Text + "' AND mahalle = '" + cmbMahalle.Text + "' AND ada = '" + txtAda.Text + "' AND parsel = '" + txtParsel.Text + "'";
However, PLEASE read about SQL INJECTION. It is a very bad security issue and this is a perfect example.

else condition not working when reader hasrows is false

Can somebody tell me why the else condition is not working in the code below.
The link button in asp.net web application has following code in code behind: a parameterized SqlCommand fetch a row from a SQL Server database, the SqlDataReader rdr1.HasRows in if condition is working fine but else condition did not work.
Code updated
protected void LinkButton1_Click(object sender, EventArgs e)
{
string comid = DropDownList4.SelectedValue.ToString();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select * from Commercials Where id =" + comid, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string dur = rdr["duration"].ToString();
Char delimiter = '/';
string[] dd = DateTime.Parse(rdr["rodate"].ToString()).ToString("dd/MM/yyyy").Split(delimiter);
if (DropDownList3.SelectedValue.ToString().Contains("BOL NEWS") == true && DropDownList1.SelectedValue.ToString().Contains("After Headlines") == true)
{
SqlConnection con0 = new SqlConnection(cs);
string sql01 = "Select * from CTS Where air_time=(Select max(air_time) from CTS where air_date=#airdate and air_time Like #airtime and channel=#channel and Slot=#slot) and air_date=#airdate1";
con0.Open();
SqlCommand cmd1 = new SqlCommand(sql01, con0);
cmd1.Parameters.AddWithValue("#airdate", TextBox1.Text);
cmd1.Parameters.AddWithValue("#channel", DropDownList3.SelectedValue.ToString());
cmd1.Parameters.AddWithValue("#airtime", DropDownList2.SelectedValue.ToString().Substring(0, 2) + "%");
cmd1.Parameters.AddWithValue("#slot", DropDownList1.SelectedValue.ToString().Remove(0, 3));
cmd1.Parameters.AddWithValue("#airdate1", TextBox1.Text);
SqlDataReader rdr1 = cmd1.ExecuteReader();
while (rdr1.Read())
{
string startTime0 = rdr1["air_time"].ToString();
string addsec = rdr1["duration"].ToString();
if (rdr1.HasRows)
{
DateTime startTime1 = DateTime.ParseExact(startTime0, "HH:mm:ss", null);
string startHeadlines_ = startTime1.AddSeconds(int.Parse(addsec)).ToString("HH:mm:ss");
using (SqlConnection con2 = new SqlConnection(cs))
{
string type = "Commercial";
string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2);
string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year;
string sql1 = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines_ + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')";
con2.Open();
SqlCommand InsertCmd = new SqlCommand(sql1, con2);
InsertCmd.ExecuteNonQuery();
con2.Close();
}
}
else
{
DateTime startTime = DateTime.ParseExact(DropDownList2.SelectedValue.ToString(), "HH:mm:ss", null);
string startHeadlines = startTime.AddSeconds(210).ToString("HH:mm:ss");
using (SqlConnection con1 = new SqlConnection(cs))
{
string type = "Commercial";
string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2);
string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year;
string sql = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.ToString().Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')";
con1.Open();
SqlCommand InsertCmd = new SqlCommand(sql, con1);
InsertCmd.ExecuteNonQuery();
con1.Close();
}
}
}
con0.Close();
}
}
con.Close();
}
}

Asp.net with c# , insert and update in save button

I am using one button named as Button 1. In Button 1 button I perform insert as well as update. I can insert a new row. But when I update the row I had a error on that:
"ORA-00933: SQL command not properly ended ".
My code is:
protected void Button1_Click(object sender, EventArgs e)
{
string UserName = "UserName";
Session["UserName"] = lb1.Text;
TextBox TextBox1 = (TextBox)FindControl("TextBox1");
Label label11 = (Label)FindControl("label11");
TextBox TextBox2 = (TextBox)FindControl("TextBox2");
TextBox TextBox3 = (TextBox)FindControl("TextBox3");
TextBox TextBox4 = (TextBox)FindControl("TextBox4");
DropDownList DropDownList3 = (DropDownList)FindControl("DropDownList3");
DropDownList DropDownList1 = (DropDownList)FindControl("DropDownList1");
TextBox TextBox5 = (TextBox)FindControl("TextBox5");
TextBox TextBox6 = (TextBox)FindControl("TextBox6");
DropDownList DropDownList2 = (DropDownList)FindControl("DropDownList2");
TextBox TextBox7 = (TextBox)FindControl("TextBox7");
TextBox TextBox8 = (TextBox)FindControl("TextBox8");
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from
service_master where req_no='" + this.TextBox1.Text.ToString() + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
string sql1 = "update service_master set req_no='" + this.TextBox1.Text.ToString() + "' , req_dt='" + label11.Text.ToString() + "',req_by='" + Session["UserName"].ToString() + "', ser_cd='" + TextBox3.Text.ToString() + "',serv_desc= '" + TextBox4.Text.ToString() + "',serv_grp_cd='" + DropDownList3.SelectedItem.Value.ToString() + "',base_uom_cd= '" + DropDownList1.SelectedItem.Value.ToString() + "',sac_cd='" + TextBox5.Text.ToString() + "',ser_long_desc='" + TextBox6.Text.ToString() + "',tax_ind='" + DropDownList2.SelectedItem.Value.ToString() + "',active_ind= '" + TextBox7.Text.ToString() + "',del_ind='" + TextBox8.Text.ToString() + "' where req_no='" + this.TextBox1.Text.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(sql1, con);
cmd.ExecuteNonQuery();
WebMsgBox.Show("Data Successfully Updated");
}
else
{
string sql = "insert into service_master(req_no,req_dt,req_by,ser_cd,serv_desc,serv_grp_cd,base_uom_cd,sac_cd,ser_long_desc,tax_ind,active_ind,del_ind ) values(" + this.TextBox1.Text.ToString() + ",'" + label11.Text.ToString() + "', '" + Session["UserName"].ToString() + "', '" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "','" + DropDownList3.SelectedItem.Value.ToString() + "','" + DropDownList1.SelectedItem.Value.ToString() + "','" + TextBox5.Text.ToString() + "','" + TextBox6.Text.ToString() + "','" + DropDownList2.SelectedItem.Value.ToString() + "','" + TextBox7.Text.ToString() + "','" + TextBox8.Text.ToString() + "')";
OleDbCommand com = new OleDbCommand(sql, con);
com.ExecuteNonQuery();
WebMsgBox.Show("The data for request number" + TextBox1.Text + "is saved");
}
con.Close();
}
}
Your query should look something like this
//insert query
//string sql1 = "INSERT INTO Test(id, name) VALUES(#User_FirstName, #User_LastName)";
//update sample query
string sql1 = "UPDATE Test SET User_FirstName=#User_FirstName, User_LastName=#User_LastName";
SqlCommand cmd = new SqlCommand(smt, _connection);
cmd.Parameters.Add("#User_FirstName", FirstName.Text);
cmd.Parameters.Add("#User_LastName", LastName.Text);
Always use Parameters to preform any database actions. Using user input is very dangerous, look up sql injections.

how to save imported excel in datagridview to database C#

how to save imported data from excel in datagridview to database in C#
I have saved records and exported to excel sheet, it exported along with data ID, now I have re-imported back to datagridview from excel. now I want to save data to database.
Important to know:
Database name "Records.sdf" using SQL Compact 3.5
DataGridViewName is RecordsDataGridView.
I'm using following code but it's not working.
public void SaveData()
{
// Save the data.
SqlCeConnection conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Records.sdf;Persist Security Info=False");
SqlCeCommand com;
string str;
conn.Open();
for (int index = 0; index < RecordsDataGridView.Rows.Count - 1; index++)
{
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '" + RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + ")";
com = new SqlCeCommand(str, conn);
com.ExecuteNonQuery();
}
conn.Close();
}
ERROR RECEIVING
Column Name not Valid, column name = Cash
Try this query string
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ",'"+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ",'" + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + "')";
You should pass varchar field enclosed with single quote.
var str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values("
+ RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '"
+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "',"
+ RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + ","
+ "'" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "'" + ","
+ RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + ","
+ "'" + dataGridView1.Rows[index].Cells[8].Value.ToString() + "'" + ")";
There are a few ways to do this.
Here is one method.
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm
You can do this as well.
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= #"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
Something like this will work too.
private void buttonSave_Click_1(object sender, EventArgs e) // save to invoice
{
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "INSERT INTO invoice (p_code, p_name, p_category, p_price) " +
VALUES (#code, #name, #category, #price)";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in MyTable.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#code", row["p_code"]);
sc.Parameters.AddWithValue("#name", row["p_name"]);
sc.Parameters.AddWithValue("#category", row["p_category"]);
sc.Parameters.AddWithValue("#price", row["p_price"]);
sc.ExecuteNonQuery();
}
con.Close();
}

How to save a picture to an access database table?

I am using this code to save a picture into an access database table:
byte[] fromPath = File.ReadAllBytes(Picture_Path);
byte[] fromPath2 = File.ReadAllBytes(BacksidePicture_Path);
con.Open();
string query = "Insert Into DML_Books_List (" +
"ID,ISNBORCode, Title, Donor, DocType, Edition, Author1, Author2, Author3, " +
"Author4, Translator, Publisher, Subject, USubject, Shelf, Cost, " +
"Language, Pages, Image, BImage, Description, Date) VALUES ('" +
"2" + "','" + ISNB_AddBook_Books_TXT.Text + "', '" +
Title_AddBook_Books_TXT.Text +
"', '" + Donor_AddBook_Books_TXT.Text + "', '" +
DocType_AddBook_Books_CBE.SelectedItem + "', '" +
Edition_AddBook_Books_TXT.Text + "', '" +
Author1_AddBook_Books_TXT.Text + "', '" +
Author2_AddBook_Books_TXT.Text + "', '" +
Author3_AddBook_Books_TXT.Text + "', '" +
Author4_AddBook_Books_TXT.Text + "', '" +
Translator_AddBook_Books_TXT.Text + "', '" +
Publisher_AddBook_Books_CBE.SelectedItem + "', '" +
Subject_AddBook_Books_CBE.SelectedItem + "', '" +
USubject_AddBook_Books_CBE.SelectedItem + "', '" +
Shelf_AddBook_Books_CBE.SelectedItem + "', '" +
Cost_AddBook_Books_TXT.Text + "', '" +
Language_AddBook_Books_CBE.SelectedItem + "', '" +
Pages_AddBook_Books_TXT.Text + "', '" +
#fromPath + "', '" + #fromPath2 + "', '" +
Description_AddBook_Books_MemoEdit.Text + "', '" +
Date_AddBook_Books_TXT.Text + "')";
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
myCommand.Connection = con;
myCommand.ExecuteNonQuery();
con.Close();
But it has some problems.
Please Help Me solve this problem.
Thank you
OleDb.OleDbConnection cn = new OleDb.OleDbConnection();
cn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Application.StartupPath + "\\data.mdb";
cn.Open();
byte[] arrImage = null;
string strImage = null;
IO.MemoryStream myMs = new IO.MemoryStream();
//
if ((this.picPhoto.Image != null)) {
this.picPhoto.Image.Save(myMs, this.picPhoto.Image.RawFormat);
arrImage = myMs.GetBuffer;
strImage = "?";
} else {
arrImage = null;
strImage = "NULL";
}
OleDb.OleDbCommand myCmd = new OleDb.OleDbCommand();
myCmd.Connection = cn;
myCmd.CommandText = "INSERT INTO tblstudent(stdid, [name], photo) " + " VALUES(" + this.txtID.Text + ",'" + this.txtName.Text + "'," + strImage + ")";
if (strImage == "?") {
myCmd.Parameters.Add(strImage, OleDb.OleDbType.Binary).Value = arrImage;
}
Interaction.MsgBox("Data save successfully!");
myCmd.ExecuteNonQuery();
cn.Close();
Source
use parameters like below code:
Assume you have two columns in your table called ID and Image. Now you going to insert data using SQL parameters
you need SQL statement like
Insert Into DML_Books_List(ID, [Image]) values (#id, #image)
#id and #image are the given names for parameters. You can set the parameter values by parameter name.
var pic = File.ReadAllBytes(yourFileName);
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("Insert Into DML_Books_List(ID, [Image]) values (#id, #image)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#image", pic);
cmd.ExecuteNonQuery();
}
Use parametrized query..
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=database");
OleDbCommand command = connection.CreateCommand();
imageData = ReadByteArrayFromFile(#"c:\test.jpg");
command.CommandText = "Insert into SomeTable (Name, ImageData) VALUES (#Name, #Img)"
command.Parameters.AddWithValue("#Name", "theName");
command.Parameters.AddWithValue("#Img", imageData);
command.ExecuteNonQuery();

Categories

Resources