C# InsertCommand Queries - c#

I have an access database connected to my project and want to save back edits. The edits only seem to save when existing values are being modified. When I insert a row or delete a row using my binding navigator, It does not update my database. I have tried many queries:
try
{
query = string.Format("SELECT * FROM {0}", Text);
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.InsertCommand = new OleDbCommand(query, conn);
adapter.DeleteCommand = new OleDbCommand(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(Account);
Console.WriteLine("Saved");
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException + ":" + ex.Message);
}
In a DataGridView.RowAdded event I added the following code:
try
{
string AccNum = accountGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
string lName = accountGridView.Rows[e.RowIndex].Cells[1].Value.ToString();
string fName = accountGridView.Rows[e.RowIndex].Cells[2].Value.ToString();
string balance = accountGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
adapter.InsertCommand = new OleDbCommand("INSERT INTO " + Text + " VALUES ("
+ AccNum + ", " + lName + ", " + fName + ", " + balance + ")", conn);
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.DeleteCommand = new OleDbCommand(query, conn);
adapter.Update(Account);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ":" + ex.InnerException);
}
In my RowAdded Event, it gives me an error and in my regular save event, everything works just fine besides the Insert and Delete Commands. Does anyone know the queries I can use to make this work?

I solved my problem by removing my RowsAdded event and all the InsertCommands and DeleteCommands. I think the problem was I was overriding the default InsertCommands and DeleteCommands with bad SqlCode.

Related

I have tried to run this update method using Oracle command but I keep getting an error as "sql command not properly ended"

My code
public void SaveEdits()
{
string SQL = "UPDATE SURVEY_CAMPAIGN SET OUTGOING_VDN =" + txtOutgoing.Value + "AND LANG_CD =" + txtlang.Value + "AND ANNOUNCEMENT_FOLDER =" + txtAnnouc.Value + "AND EXCEEDED_AUDIO =" + txtExceed.Value + "AND VALID_ENTRY_AUDIO =" + txtExit.Value +
" WHERE CAMPAIGN_ID =" + CampignsDRP.SelectedValue;
try
{
using (OracleConnection conn = SingleConnection.Instance.ActiveConn)
{
conn.Open();
OracleCommand cmd = conn.CreateCommand();
OracleDataAdapter dataAdapter = new OracleDataAdapter(SQL, conn);
System.Data.DataSet db = new System.Data.DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = SQL;
int result = cmd.ExecuteNonQuery();
dataAdapter.Fill(db, "Campaign");
cmd.Dispose();
conn.Close();
}
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "UpdateCompleted()", true);
}
catch (Exception ex)
{
string error = ex.Message;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowError('" + error + "')", true);
LogUtil.Debug("Page Campaign Update Exception Occured " + ex.Message);
}
}
string SQL = "UPDATE SURVEY_CAMPAIGN SET OUTGOING_VDN = #OUTGOING_VDN, LANG_CD = #LANG_CD, ANNOUNCEMENT_FOLDER = #ANNOUNCEMENT_FOLDER, EXCEEDED_AUDIO = #EXCEEDED_AUDIO, VALID_ENTRY_AUDIO = #VALID_ENTRY_AUDIO WHERE CAMPAIGN_ID = #CAMPAIGN_ID" ;
//Now put this parameters before int result = cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("#OUTGOING_VDN", txtOutgoing.Text);
cmd.Parameters.AddWithValue("#LANG_CD", txtlang.Text);
cmd.Parameters.AddWithValue("#ANNOUNCEMENT_FOLDER",
txtAnnouc.Text);
cmd.Parameters.AddWithValue("#EXCEEDED_AUDIO", txtExceed.Text);
cmd.Parameters.AddWithValue("#VALID_ENTRY_AUDIO", txtExit.Text);
cmd.Parameters.AddWithValue("#CAMPAIGN_ID", CampignsDRP.SelectedValue);

Parameterized Queries not working

I had the following implementation of filling a DataTable with SQL:
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
string sSQL = #"SELECT LogID, Severity, Title
FROM dbo.Log
WHERE UPPER(LogID) LIKE '%" + searchPhrase.ToUpper() + #"%' OR UPPER(Severity) LIKE '%" + searchPhrase.ToUpper() + #"%' OR UPPER(Title) LIKE '%" + searchPhrase.ToUpper() + #"%' ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + (Convert.ToInt32(current) - 1).ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
}
catch { }
This works nicely but I've realized that this is dangerous due to SQL Injection. So I've tried to solve that danger using parameterized queries like this:
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
cmd.Parameters.Add(new ObjectParameter("#searchPhrase", searchPhrase.ToUpper()));
cmd.Parameters.Add(new ObjectParameter("#orderBy", orderBy));
cmd.Parameters.Add(new ObjectParameter("#orderFrom", orderFrom));
cmd.Parameters.Add(new ObjectParameter("#current", current));
cmd.Parameters.Add(new ObjectParameter("#rowCount", rowCount));
string sSQL = #"SELECT LogID, Severity, Title
FROM dbo.Log
WHERE UPPER(LogID) LIKE '%" + searchPhrase.ToUpper() + #"%' OR UPPER(Severity) LIKE '%" + searchPhrase.ToUpper() + #"%' OR UPPER(Title) LIKE '%" + searchPhrase.ToUpper() + #"%' ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + (Convert.ToInt32(current) - 1).ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
}
catch { }
Unfortunately now my data table doesn't fill. What am I doing wrong?
You are using multiple command and connection references, not sure if thats a copy/paste problem or your actual code is like that. In the second case it will not even compile.
Reference the parameters directly in your query, see below. Sql Server uses named parameters so the same parameter can be reused in multiple locations.
Desc/Asc cannot be used as a parameter. You should double check the value though or use an enum and pass that (recommended).
The same is true of the numeric values for rowcount, pass those in as numbers or check their values using a TryParse to ensure it is numeric and not malicious code.
The default install options for Sql Server is for a case insensitive coalition. This means you do not have to UPPER a string to do a comparison. If you do have a case sensitive install then do not change this, otherwise remove all calls to UPPER when doing comparisons.
Finally you well never know why your code is not working if you surround your code in try/catch and have an empty catch block. Your code will fail silently and you will be left scratching your head. Do not do this anywhere in your code, it is bad practice!! Either catch the exception and handle it (do something so code can recover) OR log it and rethrow using throw; OR do not catch it at all. I chose the later and removed it.
Code
var currentNum = Convert.ToInt32(current) - 1;
var temp = 0;
if(!"desc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase) && !"asc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderFrom is not a valid value");
if(!int.TryParse(rowCount, out temp))
throw new ArgumentException("Rowcount is not a valid number");
var dt = new DataTable();
string sSQL = #"SELECT LogID, Severity, Title
FROM dbo.Log
WHERE UPPER(LogID) LIKE #searchPhrase
OR UPPER(Severity) LIKE #searchPhrase
OR UPPER(Title) LIKE #searchPhrase
ORDER BY #orderBy " + orderFrom + "
OFFSET ((" + currentNum.ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
using (var command = new SqlCommand(sSQL, connection))
{
cmd.Parameters.Add(new SqlParameter("#searchPhrase", "%" + searchPhrase.ToUpper() + "%"));
cmd.Parameters.Add(new SqlParameter("#orderBy", orderBy));
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
Here is a simple example of how this should be done.
con.Open();
SqlCommand cmd = new SqlCommand(#"insert into tbl_insert values(#name,#email,#add)", con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#add", txtadd.Text);
cmd.ExecuteNonQuery();
con.Close();

how to insert date(long format) into access database using datetimepicker in c# ? (error is in date part only)

Error image is here
the error is in query line , its shows syntax error
try
{
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
command.CommandText = "insert into client_table(CLIENT, DATE,BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #" + dat.ToLongDateString() + "# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
this.Hide();
employee_form f1 = new employee_form("");
f1.ShowDialog();
}
thank you in advance
In Access, dates are delimited by #, not '. Also, Access does not recognize the long date format. But dates are not stored in any format so no worries, change it to:
... + "', #" + dat.ToString() + "# ...etc.
Although if you do not parameterize your query serious damage or data exposure can be done through SQL Injection because someone could type in a SQL statement into one of those textboxes that you are implicitly trusting.
Working example:
class Program
{
static void Main(string[] args)
{
System.Data.OleDb.OleDbConnectionStringBuilder bldr = new System.Data.OleDb.OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new System.Data.OleDb.OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#" + DateTime.Now.ToString() + "#)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Update
However, you want to do something more like this which uses Parameters to protect against SQL Injection which is extremely easy to exploit so do not think that you don't really need to worry about it:
static void Main(string[] args)
{
OleDbConnectionStringBuilder bldr = new OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
OleDbParameter dobParam = new OleDbParameter("#dob", OleDbType.Date);
dobParam.Value = DateTime.Now;
cmd.Parameters.Add(dobParam);
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#dob)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
//code to write date in the access table.
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
//MessageBox.Show(dat.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
//command.CommandText = "insert into client_table(DATEE) values( '"dat.ToShortDateString()+"')";
command.CommandText = "insert into client_table (CLIENT, DATEE, BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #"+dat.ToShortDateString()+"# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
//New code for receiving the date between two range of dates
try
{
DateTime dat = this.dateTimePicker1.Value.Date;
DateTime dat2 = this.dateTimePicker2.Value.Date;
// MessageBox.Show(dat.ToShortDateString() + " " + dat2.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
string query;
query = "select * from client_table Where DATEE Between #" + dat.ToLongDateString() +"# and #" + dat2.ToLongDateString() + "# ";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Thank you all of you for the support.

Updating values in local dataBase error: CommandText property has not been initialized

I've created some sort of application that keeps a database of employees and their payments. It works well so far. But now I'm trying to implement an "update" feature, if there is some data that changes for specific user.
So I wrote the following code for the update, but I get this error:
CommandText property has not been initialized at line 105: "cmd.ExecuteNonQuery();"
Thanks !
var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
var query = "UPDATE info SET Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "' AND Data='" + dateTimePicker1.Value.ToShortDateString() + "' AND Proiect='" + textBox1.Text + "' AND Schimburi='" + label10.Text + "' AND Poza=#Poza AND Acord='" + textBox2.Text + "' AND Baza='" + textBox3.Text + "' WHERE Nume='" + label8.Text + "' AND Prenume='" + label5.Text + "'";
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You must set cmd.CommandText
//Codes
cmd.CommandText = query;
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
Add cmd.CommandText = query; above your Execution.

Data not showing in C# RichTextBox

I have a Sql Server connected to a C# form application which displays data strings. On the Sql Server side the data is saved as varChar(MAX) in all three instances. I would just like to display the data onto a RichTextBox on the form. The data is only showing a limited amount of the original data (coming out as incomplete) in the first RichTextBox (DataQualityTextBox) and it is not showing on the second and third RichTextBoxes (LoadFailureTextBox, and LoadPerformanceTextBox).
This is my code:
SqlConnection conDataBase = new SqlConnection(constring);
// POPULATING THE DATA QUALITY TAB
Query = "SELECT " + notes_field1 + ", "+ notes_field2 + ", " + notes_field3 + " FROM "+ database +" " +
" WHERE RunDate = '" + formattedDate + "'" +
" AND PackageName = '" + tdwl + "'" +
" AND Instance = '" + instance + "'; ";
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
DataQualityTextBox.Text = myReader[0].ToString();
LoadFailureTextBox.Text = myReader[1].ToString();
LoadPerformanceTextBox.Text = myReader[2].ToString();
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Thank you very much!
try:
while (myReader.Read())
{
DataQualityTextBox.Text += myReader[0].ToString();
LoadFailureTextBox.Text += myReader[1].ToString();
LoadPerformanceTextBox.Text += myReader[2].ToString();
}
or
while (myReader.Read())
{
DataQualityTextBox.AppendText(myReader[0].ToString());
LoadFailureTextBox.AppendText(myReader[1].ToString());
LoadPerformanceTextBox.AppendText( myReader[2].ToString());
}
It will Also be a good idea to use parameters in your query instead of concatenating strings

Categories