Hello i have a table called Card_tbl with a cell CardID. The problem is that when i insert only numbers like 12345 they are uploaded in the database, but when i use mix letters like Q1234R it will say INVALID COLUMN NAME Q1234R I tried many things to fix it but no success.
THE CELL IS ON VARCHAR(50) this is my code
Con.Open();
SqlCommand cmd = new SqlCommand("insert into Card_tbl values(" +txtCardNumber.Text+")", Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Admin Successfully Added!");
Con.Close();
populate();
//updateroomstate();
Clean();
the error is shown here cmd.ExecuteNonQuery();
Thank you in advance.
Solution
The correct solution is to use prepared statements. You've said the column is a varchar(50) so:
using (SqlConnection conn = new SqlConnection("yourconnectionstring"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Card_tbl VALUES (#cardNumber)", conn))
{
// we specify type VarChar and size 50, because your column is a varchar(50)
cmd.Parameters.Add("#cardNumber", SqlDbType.VarChar, 50).Value = txtCardNumber.Text;
cmd.ExecuteNonQuery();
}
}
I would also recommend that you specify the column name for the insert:
INSERT INTO Card_tbl (CardId) VALUES (#cardNumber) -- I've assumed that the column is called CardId
Why do we need parameterized queries / prepared statements?
The reason we need prepared statements is because the user could enter something malicious in the query, forcing your server to execute queries that you didn't intend.
If you have a query like this, SQL Server will do the insert and then drop the table:
INSERT INTO MyTable VALUES ('hello'); DROP TABLE MyTable; -- comment
This is a multi-statement query, meaning that the INSERT will be done first, and then the DROP TABLE will be executed. The -- denotes a comment, and everything after that in the query is discarded.
Now, if you build a query like "INSERT INTO MyTable VALUES ('" + someUserInput + "')", how could a malicious user make this query more like the previous one? Simple: enter SQL into their input.
Suppose someUserInput is '); DROP TABLE MyTable; -- comment then your query will become:
INSERT INTO MyTable VALUES(''); DROP TABLE MyTable; -- comment')
Like this, a malicious user can perform an extremely destructive operation on your database, bypass login pages, expose secret information, etc. This is a huge risk for your application.
Prepared statements work by separating the query text from the parameter values. Because they're not part of the query, they can't be interpreted as SQL. It also means that binary data types can be sent to the server as binary rather than as text. Example: DateTime.
Try this instead
Insert into Card_tbl(CardID) values('" +txtCardNumber.Text+"')"
https://www.w3schools.com/sql/sql_insert.asp
Related
How can I prevent duplicate data inserting in database?
What I like is when click button save it will show message "Cannot Insert Duplicate Value". I'm using MSAcess for my database.
Code:
connection1.Open();
OleDbCommand cmd = connection1.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Taxation (ShoesBrand, ShoesCode, ShoesColor) Values (ShoesBrand, ShoesCode, ShoesColor)";
cmd.Parameters.AddWithValue("ShoesBrand", textBox1.Text);
cmd.Parameters.AddWithValue("ShoesCode", textBox2.Text);
cmd.Parameters.AddWithValue("ShoesColor", textBox3.Text);
cmd.ExecuteNonQuery();
connection1.Close();
How do I prevent not to insert same value? Or how can i add to throw exemption when values are the same in database.
You have to create a unique index on the required column of the table. in this way, It will not allow you to insert duplicate records from C# code.
You can learn more about Unique constraints here.
Few points to be noted here. you should use using when initializing the connection. and please read about SQL injections.
This question already has answers here:
Column name or number of supplied values does not match table definition
(16 answers)
Closed 9 years ago.
con.Open();
string qry="insert into reg1 values ('"+txtname.Text+"','"+txtaddress.Text+"','"+txtpin.Text+"','"+txtage.Text+"','"+txtgender.Text+"','"+txtcourse.Text+"','"+txtcollege.Text+"','"+txtfname.Text+"','"+txtoccup.Text+"','"+txtmname.Text+"','"+txtskills.Text+"','"+txtmobile.Text+"','"+txtemail.Text+"')";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
con.Close();
I am receiving the following error message when I try to execute this code:
Column name or number of supplied values does not match table definition.
Can anyone help me find the error?
Sounds like your column numbers in your table and your SqlCommand does not match. But since we didn't know anything about your table design, we never know..
If your INSERT command and your table doesn't have the same column number, you have to declare your column names which you want to insert these values..
I count 14 columns on your table from your comment, but you try to add 13 values. These are doesn't match.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
con.Open();
string qry = #"insert into reg1
values(#name, #address, #pin, #age, #gender, #course, #college, #fname
#occup, #mname, #skills, #mobile, #email)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#address", txtaddress.Text);,
.....
cmd.ExecuteNonQuery();
con.Close();
you entered to much or to few values into the table in other words your table has 5 columns and you entered 6 values or 4 check that the values you entered corresponds with your table
best advice i can give is always use a procedure it is recommended to protect against sql injection and it will reduce the chance of this happening ,it is also a lot more efficient than hard coding it from c# end
create a proc and just call it from c# end done ;)
SQL Server stored procedure beginner's guide
create proc example_insert
#values varchar(100) <--- declare parameters
as
insert into [Table]([Column],[Column],[Column])
values('','','',)<--- -this should be the same number as your columns
calling the stored procedure this is in vb but the principle is the same
s1.Open() 'opens the connection
Dim cmd As New SqlCommand("example_insert", s1)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Value", textbox.Text)<--- a lot simpler
Hello I have a simple question that regards inserting data into a MS MySql Database 2012 table. The table that I have is called COMPLETED and has 3 fields.
student_ID (int, NOT allowed nulls)
completed (bool, NOT allowed nulls)
random_code (string, allowed nulls)
In c# I have a list filled with unique random codes. I want all codes inserted into the database, so if I have 20 records I want 20 unique codes inserted into the random_code field. So the first records gets the first code, the seconds records gets the second code and so on. I think the best way to do this is using a foreach and, for each code in the list of codes insert that code into the random_code field in my database. The problem is I don't know how to do this. I have the following code that give's me an error at VALUE:
Incorrect syntax near 'VALUE'.
foreach (string unRaCo in codes)
{
//insert database
SqlCommand toDB = new SqlCommand("INSERT INTO COMPLETED (random_code) VALUE ( '"+ unRaCo +"' ) ", conn);
SqlDataReader toDBR;
toDBR = toDB.ExecuteReader();
}
Could anyone give me a dircetion here? Thanks in advance.
EDIT:
Okay I totally changed my query as I figured out it did not yet do what I wanted it to do. I now want to update my records instead of inserting records. I did that with the following code:
foreach (string unRaCo in codes)
{
//insert database
SqlCommand naarDB = new SqlCommand("UPDATE VOLTOOID SET random_code = '"+ unRaCo +"' ", connectie);
SqlDataReader naarDBR;
naarDBR = naarDB.ExecuteReader();
naarDBR.Close();
}
The problem this time is that the update query updates ALL records with the first code, so the first record has the code 12345 for example but all other records also have that code. I want to update 12345 into record 1 and 54321 for example in number 2, how do I do that?
The correct is Values not Value, even if you only provide one column.
About your edit. First of all beware of SQL Injection. You better use SQLParameter class. Check Configuring Parameters and Parameter Data Types for further info.
If you want to update a specific id then use a where clause like (in plain SQL):
UPDATE VOLTOOID SET random_code = #NewValue WHERE random_code = #OldValue
Now if you just want to add the random number in a specific row, then you would have to use some more advanced SQL functions. Again in plain SQL you would have:
;WITH MyCTE AS
(
SELECT random_code,
ROW_NUMBER() OVER(ORDER BY random_code) AS ROWSEQ -- This will give a unique row number to each row of your table
FROM VOLTOOID _code
)
UPDATE MyCTE
SET random_code = #NewValue
WHERE ROWSEQ = #YourRandomRow
As the above queries are for SQL script execution you will need to define the variable used.
Your syntax is wrong, you are using 'value' where you should use 'values'. If you have SSMS you will able to easily figure out this kind of errors.
Usually I create the query in SQL Server Management Studio query editor, then use it in C#. Most of the times I use SQL Server stored procedures where it's possible. Because I think it cost some extra resources to execute a text query than executing a procedure
I am storing data (approx. 1500 words) in SQL server 2005 through textbox and button. I am using this code.
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
String query = String.Format("insert into try (data,sno) values ('{0}',22)",TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
Label1.Text = "submitted";
conn.Close();
}
I have column 'data' of data type 'char(4000)'.
Problem is that, when I store 1st paragraph (approx 1500 words), it stored successfully. But when I stored another paragraph (approx 1500 words), it show me the error.
"Incorrect syntax near 's'. Unclosed quotation mark after the
character string ',22)'."
What is the problem ??
Use Parameters
String query = "insert into try (data,sno) values (#data,22)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#data", TextBox1.text);
cmd.ExecuteNonQuery();
In this way you don't need to worry about the presence of single quotes in your text and, the most important thing, you avoid SqlInjection Attacks
String.Format will not escape the input string suitably for use in an SQL statement, which will lead to errors & serious vulnerabilities.
You should use Parameterized Queries which are designed specifically to address this.
This sounds like you have an ', or multiple 's, in the TextBox1.Text. You will need to replace all single quotes for double.
String query = String.Format("insert into try (data,sno) values ('{0}',22)",Replace(TextBox1.Text,"'","''"));
However, this approach will open you up to SQL Injection attacks. I'd recommend using a Stored Procedure, like the following:
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spInsertDataIntoTry";
cmd.Parameters.AddWithValue("#data", TextBox.Text);
cmd.ExecuteNonQuery();
Otherwise, you could use Parameters like others have mentioned.
Does your text contains ' letter? If yes then it is breaking INSERT query.
If you would try to insert following text:
Hello' there
Then your query would look like this:
insert into try (data,sno) values ('Hello' there,22)
Which results in incorrect query.
This is not the way queries should be done, because it leads to security issues (read more: SQL Injection) you should use parametrized queries.
"Incorrect syntax near 's' - this indicates your sql statements is wrong.
i guess that your input content maybe contains sql server keywords, so check your 2nd paragraph is there any keyword such as "'".
for example:
2nd paragraph is: how's the weather? it's cool!!!!!!!
so the sql statement is: insert into try (data,sno) values ('how's the weather? it's cool!!!!!!!',22)
it will arise an exception incorrect syntax near 's'
This is my first time I use MySQL as datastorage for my C# Application, as I've seen that there is no UNIQUEIDENTIFIER type as in SQL server I decieded to use INT with AUTO_INCREMENT, my problem is now if I execute a INSERT, how may I get the ID of the Record I just added.
My quick and dirty solution has been to execute a SELECT MAX(ID) FROM table Statement. But this doesn't seem consistent. I belive there is a better solution something like mysql_insert_id() (PHP).
Any Idea how to resolve this in C#?
You use the function last_insert_id() in a query to get the last created id:
select last_insert_id()
You have to use the same database session, i.e. the same connection object.
As you have figured out, you should not use select max(id) to get the id, as that will get the last id created by any session, not this specific session. If two inserts are done for separate users close in time (so that both inserts happen before one of them do the select to get the id), they will both get the id of the last insert.
The solution of Guffa is a possibility, thanks for this, but I figured out that I can use also LastInsertedId on my Command, a short example:
MySqlCommand cmd = new MySqlCommand("INSERT INTO users (Username, Prename, Lastname, Password) VALUES (\"" +
user.Username + "\",\"\", \"\",\"\")", new MySqlConnection(u.ConnectionString()));
cmd.CommandType = CommandType.Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
But this doesn't work if the command executes a Stored Procedure.
Regards,
Johannes