How do i update the Yes/No Field Select Column using c#?
Here's my table 1 and table 2:
Here is my code:
connection.Open();
OleDbCommand command = new OleDbCommand("update [Table1] set [Select] = #Select, [DocumentName] = #DN where [Table1ID] = " + txtTable1ID.Text + " ", connection);
command.Parameters.AddWithValue("#Select", checkBox1.Checked);
command.Parameters.AddWithValue("#DN", "Form 137");
command.ExecuteNonQuery();
command.Parameters.Clear();
command.Parameters.AddWithValue("#Select", checkBox2.Checked);
command.Parameters.AddWithValue("#Name", "Good Moral");
command.ExecuteNonQuery();
command.Parameters.Clear();
command.Parameters.AddWithValue("#Select", checkBox3.Checked);
command.Parameters.AddWithValue("#Name", "Transcript of Record");
command.ExecuteNonQuery();
connection.Close()
The output with this code:
You miss a comma:
"update [Table1] set [Select] = #Select, [DocumentName] = #DN where [Table1ID] = " + txtTable1ID.Text + ""
Please be aware that your code is vulnerable to SQL Injection attacks.
You should never concatenate SQL like this: [Table1ID] = " + txtTable1ID.Text + " ".
Instead use parametised SQL, like you've done for other bits, such as the "#Select" parameter.
(Sorry, not enough rep to post this as a comment)
Related
please figure out the error in my code.it show syntax error INSERT INTO statement.
OleDbCommand cmd = new OleDbCommand("INSERT INTO tbbill(invoice,datetime,custm,total,tax,grand)VALUES(" + Convert.ToInt32(txtinvoice.Text) + ",'" + dateTimePicker1.Value.ToString("yyyy/MMM/dd") + "','" + Convert.ToString(txtcn.Text) + "','" + txtttl.Text + "','" + Convert.ToInt32(cmtax.Text) + "','" + txtgrdttl.Text + "')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
It seems that you've commited all the sins possible in this short fragment.
Something like that is expected:
// Make SQL readable
String sql =
#"INSERT INTO tbbill(
invoice,
[datetime], /* reserved word */
custm,
total,
tax,
grand)
VALUES(
?, ?, ?, ?, ?, ?)"; // Make SQL parametrized
// Put IDisposable into "using"
using (OleDbCommand cmd = new OleDbCommand(sql, con)) {
// Parameterized
cmd.Parameters.Add(txtinvoice.Text);
cmd.Parameters.Add(dateTimePicker1.Value);
cmd.Parameters.Add(txtcn.Text);
cmd.Parameters.Add(txtttl.Text);
cmd.Parameters.Add(cmtax.Text);
cmd.Parameters.Add(txtgrdttl.Text);
cmd.ExecuteNonQuery();
}
// Do not close that's not opened by you (i.e. con)
Apart from your weird INSERT statement, your column name datetime is a reserve word in Access. You should escape it suing [] like below.
INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand)
Your current query is open to SQL Injection and so as suggested in comment consider using parameterized query instead.
This should work:
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand)
VALUES(" + Convert.ToInt32(txtinvoice.Text) + ",\"" +
dateTimePicker1.Value.ToString("yyyy/MMM/dd") + "\",\"" +
Convert.ToString(txtcn.Text) + "\",\"" + txtttl.Text + "\",\"" +
Convert.ToInt32(cmtax.Text) + "\",\"" + txtgrdttl.Text + "\")", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
EDIT:
As stated by others, your query is still open to SQL injection. Dmitry's answer will be the safest and efficient option.
I've been stumbling over this issue without being able to configure whats wrong in my sql insert statement. I need to insert a new row in a table but
it keeps telling me that the columns in the insert statement are more than these in the clause.
Here is my statement:
kSqlCommand.CommandText = "INSERT INTO BillsDetails ([BillID],[CallDialledID],[CallDateTime],[CallDuration],[CallNetPrice],[CallRetailPrice],[CallDiscountPrice]) VALUES ('" + strBillID + "','" + strDialledNumberID + "','" + strCallDate + "','" + strCallDuration + "','" + dCallNetPrice + "','" + dCallRetailPrice + "','" + dCallDiscountPrice + "')";//SqlStatement to Add new Bill
kSqlCommand.ExecuteReader();
and each time I get this error:
"There are more columns in the INSERT statement than values specified
in the VALUES clause using c#. The number of values in the VALUES
clause must match the number of columns specified in the INSERT
statement."
apparently, its a syntax issue, since columns in the INSERT statement = number of given values.
any help will be appreciated..
string cmdString="INSERT INTO BillsDetails('BillID','CallDialledID','CallDateTime','CallDuration','CallNetPrice','CallRetailPrice','CallDiscountPrice') VALUES (#val1, #va2, #val3,#val4, #va5, #val6,#val7)";
string connString = "your connection string";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandString = cmdString;
comm.Parameters.AddWithValue("#val1", 'your value');
comm.Parameters.AddWithValue("#val2", 'your value');
comm.Parameters.AddWithValue("#val3", 'your value');
comm.Parameters.AddWithValue("#val4", 'your value');
comm.Parameters.AddWithValue("#val5", 'your value');
comm.Parameters.AddWithValue("#val6", 'your value');
comm.Parameters.AddWithValue("#val7", 'your value');
try
{
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
Catch(SqlException e)
{
}
}
}
I think try use of ExecuteNonQuery instead of ExecuteReader
because ExecuteReader is reading database content instead of insertion of row
please read this article https://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.110).aspx ,.
I want to fetch the random string generated in the access DB and display it using message box.
eg: if i enter a name "xyz" the random number generated to the corresponding name should be displayed in the message box..
i tried these codes but its displaying the name entered in the textbox
command.CommandText = "insert into Booking(Flightno,sName) values('" + comboBox3.Text + "','" + textBox1.Text + "')";
command.ExecuteNonQuery();
string query = "select Freightno from Booking where sName=" + "\"" + textBox1.Text + "\"";
command.CommandText = query;
MessageBox.Show(query);
//MessageBox.Show("Succesfully booked");
Thank you
Of course, to get out anything from a database you need to do something with your command.
If you want to read something various options exists, but when you need only one value the best approach is using ExecuteScalar.
command.CommandText = "insert into Booking(Flightno,sName) values(#p1,#p2)";
command.Parameters.AddWithValue("#p1", comboBox3.Text);
command.Parameters.AddWithValue("#p2", textBox1.Text);
command.ExecuteNonQuery();
// Clear the parameters collection to reuse the same command
command.Parameters.Clear();
command.Parameters.AddWithValue("#p1", textBox1.Text);
// Change the commandtext to the new query
command.CommandText = "select Freightno from Booking where sName=#p1";
string result = command.ExecuteScalar().ToString();
MessageBox.Show(result);
I am trying to do an insert query and I keep getting the error:
incorrect syntax near '/'
Here is what I am inserting " /Portals/0/products/HT3-XXX.pdf "
Why can I not insert the '/' ?
Do I need to convert to string? or what?
//Inserts 3DModel
SqlConnection sqlCon2 = new SqlConnection("...");
SqlCommand sqlCmd2 = new SqlCommand();
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', " + textBox15.Text + ", " + textBox4.Text + ") ";
sqlCmd2.Connection = sqlCon2;
sqlCon2.Open();
sqlCmd2.ExecuteNonQuery().ToString();
sqlCon2.Close();
MessageBox.Show("3DModel for " + textBox3.Text + "' Has been Added");
Most likely, it's complaining about the URL you're using as a parameter.
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', " + textBox15.Text + ", " + textBox4.Text + ") ";
sqlCmd2.Connection = sqlCon2;
Parameterize your query and see if it fixes the issue:
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES (#TypeId, #ProductId, #Url) ";
sqlCmd2.Parameters.AddWithValue("#TypeId", 3);
sqlCmd2.Parameters.AddWithValue("#ProductId", textBox15.Text);
sqlCmd2.Parameters.AddWithValue("#Url", textBox4.Text);
sqlCmd2.Connection = sqlCon2;
Well the problem is because you are missing single quotes around the values in your concatenated query. But your query is prone to SQL Injection. Use SqlParameter.
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', #ProductID, #URL)";
sqlCmd2.Parameters.AddWithValue("#ProductID", textBox15.Text);
sqlCmd2.Parameters.AddWithValue("#URL", textBox4.Text);
Consider using using statement with your Connection and Command object to release resources.
You'd have to wrap the value in quotes for SQL to understand that it's a string:
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', " + textBox15.Text + ", '" + textBox4.Text + "') ";
However, this code is extremely vulnerable to SQL injection attacks. I'd strongly recommend using a prepared statement instead:
sqlCmd2.CommandText = "INSERT INTO [Products].[Files] ([TypeID] ,[ProductID] ,[URL]) VALUES ('3', #productID, #url) ";
sqlCmd2.Parameters.AddWithValue("#productID", textBox15.Text);
sqlCmd2.Parameters.AddWithValue("#url", textBox4.Text);
You're currently using the raw content of your text fields. This is a VERY bad idea, because first of all you can't make any characters that might terminate the SQL statement. Second of all, as a result of this, anyone could write a query that drops the entire database.
Now, to answer your question, you're missing quotes around the textboxes.
Currently it could say:
('3', Textbox5ContentHere, Textbox4ContentHere)
When you want
('3', 'Textbox5ContentHere', 'Textbox4ContentHere')
#Edit: Downvoters, please explain.
Say I have a basic query, something like this:
SELECT holiday_name
FROM holiday
WHERE holiday_name LIKE %Hallow%
This executes fine in my sql query pane and returns 'Halloween'. My problem occurs when I try to use parameters with with the wildcard '%' characters in my code.
SqlConnection Connection = null;
SqlCommand Command = null;
string ConnectionString = ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString;
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE %#name%";
Connection = new SqlConnection(ConnectionString);
try
{
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
Command.Parameters.Add(new SqlParameter("name", HolidayTextBox.Text));
var results = Command.ExecuteScalar();
}
catch (Exception ex)
{
//error stuff here
}
finally
{
Command.Dispose();
Connection.Close();
}
This throws an incorrect syntax error. I've tried moving the '%' to my parameter like so
Command.Parameters.Add(new SqlParameter("%name%", HolidayTextBox.Text));
but then I receive an error saying I haven't declared the scalar variable '#name'. So, how do you properly format wildcard characters to be included with query parameters? Any help is appreciated!
First off, your SqlParameter name is #name not name.
Second, I would move your wildcards.
So it would look like this:
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE #name;"
Connection = new SqlConnection(ConnectionString);
try
{
var escapedForLike = HolidatyTextBox.Text; // see note below how to construct
string searchTerm = string.Format("%{0}%", escapedForLike);
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
Command.Parameters.Add(new SqlParameter("#name", searchTerm));
var results = Command.ExecuteScalar();
}
Note that LIKE requires special care when passing parameters and you need to escape some characters Escaping special characters in a SQL LIKE statement using sql parameters.
whatever you do don't do this:
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE '%'" + HolidayTextBox.Text + "'%'";
as that will open you up to sql injection, instead do this:
Command.Parameters.Add(new SqlParameter("#name", "%" + HolidayTextBox.Text + "%"));
you may like to know about Command.Parameters.AddWithValue, e.g:
Command.Parameters.AddWithValue("#name", "%" + HolidayTextBox.Text + "%");
The %s should be part of the search string, not the query.
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE #name";
Connection = new SqlConnection(ConnectionString);
try
{
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
string name = "%" + HolidayTextBox.Text + "%";
Command.Parameters.Add(new SqlParameter("#name", name));