I am really new to ASP.NET, C#.
Now I am trying to write a little method, what is build me an sql query.
(Later I will use prepared statements, now I am just try to get acquainted with the environment, with the language, etc...)
Here is my method:
public void insert( string table, Dictionary<string, string> dataToInsert ) {
string sql = "INSERT INTO " + table;
if (dataToInsert.Count< 1) {
throw new Exception("No data to insert to table: " + table);
}
List<string> fieldNames = getFieldNames(dataToInsert);
List<string> aposthrofedFieldNames = getApostrophedValues(fieldNames);
List<string> values = getValues(dataToInsert);
List<string> aposthrofedValues = getApostrophedValues(values);
string fieldNamesString = string.Join(", ", aposthrofedFieldNames);
string valuesString = string.Join(", ", aposthrofedValues);
sql += " (" + fieldNamesString + ") VALUES (" + valuesString + ")";
}
The fieldNamesString and valuesString are just concatenated strings like `'userId', 'loginDate', ... so nothing special, just strings.
At this line:
sql += " (" + fieldNamesString + ") VALUES (" + valuesString + ")";
the sql variable has gone. Can not be watchable, no more datatip.
What do I do wrong?
EDIT
Screenshot:
UPDATE
If I am using this, sql will be ok:
sql = string.Concat(sql, " (", fieldNamesString, ") VALUES (", valuesString, ")");
Related
I'm confused at the moment about what it means exactly about my current syntax error issue while trying to save/insert answers into a table in my database. It worked fine when I attempted this with hardcoded variables but now is not the case.
Part of the error message:
Additional information: Incorrect syntax near ')'
Not sure what I'm doing wrong. Below is the code I'm using and the location where the error is pointing to. Thank you for any possible assistance and clarification.
protected void btnSaveAnswers_Click(object sender, EventArgs e)
{
Int32 int32StudentID = Convert.ToInt32(Session["StudentID"]);
Int32 int32QuestionID = Convert.ToInt32(Session["QuestionID"]);
String strAnswer = "";
// Save the student's answer to the Answer table.
// Develop the SQL call.
String strSQL = "";
strSQL = "INSERT ";
strSQL += "INTO Answer ";
strSQL += " (StudentID, QuestionID, Answer) ";
strSQL += "VALUES ";
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", " + strAnswer + ")";
// Define the network connection to the SQL Server database.
SqlConnection objSqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["OPT"].ConnectionString);
// Create the SQL command object.
SqlCommand objSqlCommand = new SqlCommand();
objSqlCommand.Connection = objSqlConnection;
objSqlCommand.CommandType = CommandType.Text;
objSqlCommand.CommandText = strSQL;
// Open the connection.
objSqlConnection.Open();
// Execute the Insert statement.
objSqlCommand.ExecuteNonQuery();
// Close the connection.
objSqlConnection.Close();
this.Master.MessageForeColor = System.Drawing.Color.White;
this.Master.Message = "You have saved your answer for this question, click next to continue.";
}
First you should not be building SQL statements like this, it is prone to many problems, but your issue is with your string, you do not have single quotes around it:
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";
Need to add the single quotes around strAnswer like I have above
Use parameters outlined here:
https://msdn.microsoft.com/library/bb738521(v=vs.100).aspx
I agree with the comment about concatenation of strings. If you have to write a SQL query in code, you should user string interpolation.
If I had to do it, I would write it like this:
String strSQL = $"INSERT INTO Answer (StudentID, QuestionID, Answer) VALUES ( {int32StudentID}, {int32QuestionID}, '{strAnswer}')";
That said, that is not why you have a syntax error. You are missing single quotes around your string variable. Try this:
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";
The error is at this line
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", " + strAnswer + ")";
As per your SQL Query and database the field Answer is a field of type varchar or nvarchar. This type of field always takes value of string type. Which is done by you already. But SQL Server database accept these values inside the single quotation ''. Thus your solve is
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";
as I've added a single quotation in front of strAnswer and at the last of strAnswer
Thank you.
I have below string
string str= "Insert into " + tname + "(id, t, v) values(" + lc+ ", " + mc+ ", " + rc+");" + Environment.NewLine;
and I'm write it to file:
File.AppendAllText(fileName, str);
It's working.
I also tried to use string.Join:
string str = string.Join("Insert into " + tname+ "(id, t, v) values(" + lc+ ", " + mc+ ", " + rc+ ");", Environment.NewLine);
File.AppendAllText(fileName, str);
but the file always is empty. What is wrong?
i think what you need is string.Format()
string str = string.Format("Insert into {0}(id, t, v) values({1}, {2}, {3});{4}",tname, lc,mc,rc, Environment.NewLine);
String.Format() documentation
string.Join is to concatenate a String[] of objects using a separator
eg
List<int> l= new List { 1,2,3 };
var s = string.Join(",",l);
s is then "1,2,3"
In your code you are basically passing in a very long separator (your string) and an empty array.
Documentation for string.Join
i would like to insert multiple data into my database. I am using for-each statement to get the data and when i insert into the database, it generates 10(just a random no. depending on the no. of data i retrieved) rows for me with one data in every row instead of all in one row. here is the for-each statement i am using.
foreach(var kiev in dict)
{
string na = kiev.Key;
if(na != "db_table_name")
{
string quer = "insert into " + HttpContext.Current.Session["tablename"].ToString() + " ( " + kiev.Key + " ) VALUES ( '" + kiev.Value + "' ) ";
SqlCommand cl = new SqlCommand(quer, con);
cl.ExecuteNonQuery();
}
}
There are better options like "SqlBulkCopy" available as already mentioned in the comments but also something like this should work:
string tablename = "";
string values = "";
string keys = "";
foreach(var kiev in dict)
{
string na = kiev.Key;
if(na != "db_table_name")
{
keys += kiev.Key + ", ";
values += "'" + kiev.Value + "', ";
}
}
keys = keys.Remove(keys.Length - 2);
values = values.Remove(values.Length - 2);
string quer = "insert into " + HttpContext.Current.Session["tablename"].ToString() + " ( " + keys + " ) VALUES ( " + values + " ) ";
SqlCommand cl = new SqlCommand(quer, con);
cl.ExecuteNonQuery();
am writing a c# code in which am trying to update 4 of the 10 columns of the table. Here is my function type in which am sending arguments for the query:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
Now what happens is that i call this function somewhere in my program providing values in argument:
checkout_visitor(chk_in,chk_out,t_out,dt_out,idcardnum);
The query am using to update my columns is given by:
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = "+ v_idd;
Given me exception incorrect syntax near chkout. Where am i wrong?? is the syntax correct? how do i correct it?
code:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
{
try
{
connection.Open();
String query = "select v_id from visitor where visitor.cnic=" + cnic;
command = connection.CreateCommand();
command.CommandText = query;
visitor_id = command.ExecuteScalar().ToString();
int v_idd = Int32.Parse(visitor_id);
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = " + v_idd;
//String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = " + time_out + ",[date_out] =" + date_out + " where visit_detail.v_id = " + v_idd;
command = connection.CreateCommand();
command.CommandText = query2;
int result = command.ExecuteNonQuery();
connection.Close();
return result;
}
catch (Exception e)
{
return -1;
}
}
Problem :
1.you are not seperating the Parameters properly using comma , .
2.you are not giving the sapace between SET and check_in parameter.
Try This:
String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = '" + time_out + "',[date_out] ='" + date_out + "' where visit_detail.v_id = "+ v_idd;
Do you see the resulting query? It seems to me you're missing some comma, but you should print (and post) the resulting query to have a better understanding of the issue.
You are missing ',' between the column names.
Its like Update Table Set col1=3,col2='test'
The problem is that query2 string will be something along the lines:
UPDATE visit_detail SET[check_in] = " 1[check_out] = 2[time_out] = some time[date_out] =some datewhere visit_detail.v_id = 5
So you can already see that there's datewhere that is incorect, there are also no ' characters around string parameters, and no commas between parameters.
Quick fix to that would be:
String query2 = String.Format("UPDATE visit_detail SET [check_in]={0}, [check_out]={1}, [time_out]='{2}', [date_out]='{3}' where visit_detail.v_id={4};", check_inn, checkout, time_out, date_out, v_idd);
But this is still not valid. If time_out contains ' characters, you'll again receive an error.
What you should really use is this:
SqlCommand.Parameters
This is a proper way of passing paramters to your command, all the problems will be taken care of for you.
This is my code:
OleDbConnection con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "/shoping mall.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("update RecordofItems set RecordofItems.Bill_no = " + textBox1.Text + ", RecordofItems.Received_from = '" + textBox62.Text + "', RecordofItems.Item_Code = " + textBox2.Text + ", RecordofItems.Quantity = " + textBox32.Text + ", RecordofItems.Sale_Rate = " + textBox47.Text + " where Item_Name = '" + textBox17.Text + "'", con);
int x = 0;
x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("record deleted" + x);
}
else
{
MessageBox.Show("no record exixt");
}
con.Close();
I want to update selected columns in my "RecordofItems" table that has 10 columns but I want to update only 6 selected columns, when I run the query it shows error "no value for one or more required paremeter" What to do ? please help me as soon as you can.
the error No value given for one or more required parameters usually comes when you have misplaced single quote.
try these two.
try assigning your numerical db columns a numerical value viz update your query with these:
RecordofItems.Bill_no = " + Convert.ToInt32(textBox1.Text) + ",
RecordofItems.Item_Code = " + Convert.ToInt32(textBox2.Text) + ",
RecordofItems.Quantity = " + Convert.ToInt32(textBox32.Text) + ",
RecordofItems.Sale_Rate = " + Convert.ToInt32(textBox47.Text) +
or use whatever suitable numerical converter applies to your columns.
one of your text fields might have a single quote in it, so try replacing/updating your text fields like this:
RecordofItems.Received_from = '" + textBox62.Text.Replace("'","''") + "',
so basically, replace single quote with two single quotes.
see if these solve your issue.
Also, do note, never create your sql query by concatenating textboxes(strings). use command parameters. they will save you from sql injection.