Error: wrong syntax near '_1_txt' - c#

Unfortunately my Code does not work: It always throws the error: Wrong syntax near '_1_txt'. Thanks in advance!
This is my Code:
protected void btnSpeichern_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO tbl_mag(1_1_txt) VALUES(#1_1_txt)";
{
cmd.Parameters.AddWithValue("#1_1_txt", txt1.Text.Trim());
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}

Column names generally shouldn't (or in some cases can't) begin with a number. Ideally you should change your schema to follow this rule, but if you can't then at the very least you would need to explicitly specify the name as an identifier. In SQL Server that's done with square brackets:
INSERT INTO [tbl_mag] ([1_1_txt]) VALUES (#1_1_txt)

This maybe answered by this post:
Syntax Error when the column name contains underscore
Basically you have to Sql Escape the columns names by wrapping them in square brackets.
1_1_txt --> [1_1_txt]

Related

How to insert to service based database?

I read lots of topics and tried many solutions, but it is not working for me, to insert my data to the database.
public static void Feltoltes(string szo_var, string szotagolva_var)
{
string query = "";
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
{
command.Parameters.Clear();
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES ('#szo','#szotagolva')";
command.Parameters.AddWithValue("#szo", szo_var);
command.Parameters.AddWithValue("#szotagolva", szotagolva_var);
System.Windows.Forms.MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
}
conn.Close();
}
}
This is my code. My connection string is the right one. If I insert to the database manually, than I can make SELECTs etc. Only the Insert is not working properly. It don't get any exception, looks like everything works, but nothing changes.
Every thing looks OK except for the insert command text.
Try the following:
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES (#szo,#szotagolva)";
If you use single quates (') inside a SQL command text it will treat what is inside as a literal. And hence it cancels out your parameter designation #

Error on passing values in SqlCommand query

What am I doing wrong here? I just want a dynamic method which can count any column depending on the value. But getting a runtime error.
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '='."
public class DataAccessLayerPayroll
{
public static string CountTblColumByValue(string columName,string value)
{
String cs = ConfigurationManager.ConnectionStrings["BD_CompanyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string sqlQuery ="Select Count("+columName+") from tblAttendance1 where"+columName+"='"+value+"'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
con.Open();
object count = cmd.ExecuteScalar();
return count.ToString();
}
}
}
The issue here is that you're missing some space between where "+columName+"= '"+value+"'"
But the bigger issue is that your command is exposed to SQL injection. To prevent this use parameterized queries.
Change it as the following way
public static string CountTblColumByValue(string columnName, string value)
{
String cs = ConfigurationManager.ConnectionStrings["BD_CompanyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string sqlQuery ="Select Count(#myColumName) from tblAttendance1 where #myColumName = #myValue ";
using(SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
con.Open();
cmd.Parameters.AddWithValue("#myColumName", columnName);
cmd.Parameters.AddWithValue("#myValue", value);
object count = cmd.ExecuteScalar();
return count.ToString();
}
}
}
string sqlQuery ="Select Count("+columName+") from tblAttendance1 whereYOU ARE MISSING A SPACE HERE"+columName+"='"+value+"'";
So your code must be like following:
string sqlQuery ="Select Count("+columName+") from tblAttendance1 where "+columName+"='"+value+"'";
The basic error in your code is missing space between where and =
Also, You should definitely fix the SqlInjection as suggested in other answers. (You cannot use parameters for column name though)
After that, you also should see that according to Count definition you will only get count of not null values.
Count() function returns the number of records in a select query (only Not Null) values.
Also see how will you achieve following:
1) count null values only
2) count all not null values
3) count number/date operations i.e. <, >, between
If you don’t need these scenarios in your code, then you have the answer to the error in your sql.

How to use a parameter for a SQL Server query that is part of the query itself using SqlDataReader in C# asp.net

Background
I am trying to retrieve the count of occurrences of a user in the database at the same time as returning the data set. How do I accomplish this? My code is below of what I have so far.
If I hard code the username, for the row, I get the expected output. However, I am having problems declaring a parameterized query variable with this code. Any help would be appreciated. I have been working on this for quite some time now.
protected void Page_Load(object sender, EventArgs e)
{
string ConnStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string Command = "SELECT TOP 3 *, Counter = (select Count(User) from Projects where [User]='jmoore00' AND Account = 'ACTIVE') FROM Projects";
using (SqlCommand comm = new SqlCommand(Command, conn))
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
ListView.DataSource = rdr;
ListView.DataBind();
rdr.Close();
}
}
}
Above, 'jmoore00' should be scalar variable #User but how do I appropriately declare and use the variable with value equaling rdr["user"] if I am using the code the way it is?
I think you should use Stored Procedure in you sql.as a specific user try to retrieve its data, do add number of this occurrence to a field in your sql.
each user has a unique field which can be in access with their users or userID.
but i think it will increase transaction time .
hope it would be helpful

Inserting value into database

I wanted to insert values into database but it is not working eventhough my code perfectly working when its used as stored procedure. I am trieng to use button click to store the value. Please tell whats wrong with the code. Its not showing any error or exception but data is not getting updated in the table
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES ('12', 'abcd', '20')";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
my columns acnum and shares_bought are "int" and scripname is
"varchar"
Then you will not need single quotes for your integer values. Use it as;
...VALUES (12, 'abcd', 20)"
A few things more;
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
You don't need cmd.CommandType = CommandType.Text line. It is .Text by default.
var conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
using(var sqlConnection1 = new SqlConnection(conStr))
using(var cmd = sqlConnection1.CreateCommand())
{
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES (12, 'abcd', 20)";
sqlConnection1.Open();
cmd.ExecuteNonQuery();
}
Set breakpoint in code and see if code is executing. In case you don't know how to, see here.
As you are not getting any exception on insert statement and it's not reflecting in database, either you have different connection string or your code is not getting executed.

Error "Incorrect Syntax Near '/'

I got a problem with my C#, whenever i try to save new data in the database coming from serial comm an error comes out and says
Incorrect Syntax Near '/'
I tried every suggestion everyone gave but it just wont stop..Here it is the piece of code where it comes out.
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SqlConnection cn = new SqlConnection(global::test_new.Properties.Settings.Default.Database3ConnectionString);
try
{
string sql = "INSERT INTO PowerData (Date/Time,Power(W)) values(" + this.powerTextBox.Text + ",'" + this.powerTextBox.Text + "'");
SqlCommand exeSql = new SqlCommand(sql, cn);
cn.Open();
exeSql.ExecuteNonQuery();
this.powerDataTableAdapter.Fill(this.database3DataSet.PowerData);
}
catch (Exception ex)
{
}
}
You need to escape special characters in table and column names like /
INSERT INTO PowerData ([Date/Time], Power(W)) values ...
In MySQL use backticks to escape, in MSSQL use brackets.
You've got some crazy column names there. If you want to include special characters in column names like that then you must wrap them in brackets in SQL, e.g. [Date/Time]. A better idea would be to not use such characters in the first place.
syntax should be like below, escape all columns with special characters
INSERT INTO PowerData
([Date/Time], [Power(W)])
VALUES
(GETDATE(), 'test1')
DEMO
First, "this.powerTextBox.Text" - I am guessing this shouldn't be the same value for both variables
change your code to this:
DateTime dt = DateTime.Parse(this.powerTextBox.Text);
string PowerW = this.powerTextBox.Text;
string sql = "INSERT INTO PowerData ([Date/Time],[Power(W)]) values(#val1, #val2);"
SqlCommand exeSql = new SqlCommand(sql, cn);
exeSql.Parameters.AddWithValue("#val1", dt);
exeSql.Parameters.AddWithValue("#val2", PowerW);
cn.Open();
exeSql.ExecuteNonQuery();

Categories