String or binary data would be truncated. SQL Statements in C# - c#

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=; Database=; User id=; password=";
conn.Open();
string Query = "Insert into [Capstone0480].[dbo].[NAME] (NameID, FirstName, MI, LastName, UserID) Values('" + this.txtNameID.Text + "','" + txtFirst.Text + "','" + txtMI.Text + "','" + txtLast.Text + "', '" + txtUserID.Text + "')";
SqlCommand createCommand = new SqlCommand(Query, conn);
createCommand.ExecuteNonQuery();
MessageBox.Show("Updated");
conn.Close();
I have been getting this error on the ExecuteNonQuery() statement. I am not sure what is wrong here. I feel as if my sql statements are correct. I am just trying to add what is typed into textboxes into my database.
If there is a better way of doing this or if there is something wrong, please let me know!

One of the columns in your NAME table is shorter than the values you are trying to insert into it.
Try trimming the length of your name textboxes before you insert them into the database, or alternatively increase the length of your database columns.
For example:
If your FirstName Column is varchar(20)
then:
var firstName = txtFirst.Text.Length > 20 ? txtFirst.Text.Substring(0,20) : txtFirst.Text;
then insert the value of firstName into your SQL statement.
In addition, you should set the max length of your Textbox to be no more than the size of your columns.

The error suggest, that your input data length is more than the column length you define in database table.
suppose the column is like
TableName1
ColumnName1 varchar(50)
and now when you want to insert 51 or more character length input string, at that time the Sqlserver gives error. check this sample example.
declare #t table (name varchar(5))
insert into #t values('abc')
select * from #t
insert into #t values('abcdefg') --this gives error as you insert more than define length.
Please check at run-time what is the input string.
Good if you restrict your textbox to insert only the database column length like
<input type="textbox" maxlength="50" />

Related

Inserting data in an sqlserver using the column name from a control. c#

I am trying to insert data in an SQL table by executing an Insert Query.
The problem is that I need to get the column name from a cell in the selected gridview Row.
Here's the snippet:
SqlCommand cmd30 = new SqlCommand("insert into mytable ( '"+GridView7.SelectedRow.Cells[0].Text+"' , r_id) values ('"+ GridView7.SelectedRow.Cells[1].Text +"', '"+TextBox1.Text+"')",con30);
cmd30.ExecuteNonQuery();
r_id is not a Primary Key.
Error is:
Incorrect syntax near 'r_id'.
Any Help will be appreciated.
Thanks.
Use SqlCommand Parameters.
Also make sure you get valid column name from GridView7.SelectedRow.Cells[0].Text;
Code:
string col1 = GridView7.SelectedRow.Cells[0].Text;
string sql = "INSERT into mytable (" + col1 + ", r_id) Values (#" + col1 + ", #rid)";
SqlCommand cmd30 = new SqlCommand(sql, con30);
cmd30.Parameters.AddWithValue("#" + col1, GridView7.SelectedRow.Cells[1].Text);
cmd30.Parameters.AddWithValue("#rid", TextBox1.Text);
cmd30.ExecuteNonQuery();

Inserting values into table from textboxes & from another table's foreign key C#

Im trying to insert into a table values from textboxes AND to retrieve a foreign key id from another table and insert that also.
So I have a users table which contains UserId and I want this inserted into a nutrition diary which includes all the data that comes from textboxes(ie Weight, Height, Date etc)
I am retrieving the MemberId by using a session to track the username(lblRegistered)
Here is my code:
SqlConnection con = new SqlConnection("path for my connection");
con.Open();
SqlCommand cmd = new SqlCommand("select COUNT(*)FROM Members where Username='" + lblRegistered.Text + "'", con);
con.Close();
con.Open();
cmd.CommandText = "INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId) values ('" + txtWeight.Text + "','" + txtHeight.Text + "','" + txtBmi.Text + "','" + txtDate.Text + "','" + txtWater.Text + "','" + txtCalorie.Text + "', Select Users.UserId From Users where (Users.Username= '" + lblRegistered.Text + "'))";
cmd.ExecuteNonQuery();
cmd.Clone();
con.Close();
Response.Redirect("Success.aspx");
The error is close to Select Users part.
Any help would be greatly appreciated!
First thing would be to read up on parameterized SQL queries. The code you have there is completely open to SQL injection attacks.
This is a good resource for that: http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Then for the problem you would be better off using a Stored Procedure to do the work. Something along the lines of :
CREATE PROCEDURE Nutrition_Insert
#weight varchar(10),
#height varchar(10),
#bmi varchar(10),
#date varchar(10),
#username varchar(10),
//etc for your fields
AS BEGIN
DECLARE #memberId varchar(10)
SELECT #memberId = UserId From Users where Username = #username
INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId)
values (#weight, #height, #bmi, ....., #memberId)
END
Note - I've made some assumptions there as I don't know your data types, they all look like strings, but not knowing the size of the varchar used, I picked an arbitary value. Replace the (10) with the actual field size.
If you must use embedded SQL - then this is how you parameterize it. I've also fixed the insert statement to pull the MemberId from the Members table as part of the insert.
using (var conn = new SqlConnection("YOUR CONNECTION STRING"))
{
conn.Open();
using (
var cmd = new SqlCommand(
"INSERT INTO Nutrition(...fields...) SELECT #Weight, #Height, #Bmi,...., Members.MemberId FROM Members WHERE Members.Username = #Username", conn)
)
{
cmd.Parameters.AddWithValue("#Weight", txtWeight.Text);
cmd.Parameters.AddWithValue("#Height", txtHeight.Text);
...
cmd.Parameters.AddWithValue("#Username", lblRegistered.Text);
cmd.ExecuteNonQuery();
}
conn.Close();
}
You'll notice the using statements too. This will make sure your connection are disposed of cleanly.
Hope that helps.
Thanks Richard..that worked very well on the problem.
I am just trying to do the same technique on a different page but this time it will have 2 where clauses
var cmd = new SqlCommand("INSERT INTO AssignPlan(Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId) Select #Reps, #Sets,#WeightOrTime,#Date, Members.MemberId From Members Where Members.Username=#name,ExerciseDisplay.ExerciseId From ExerciseDisplay Where ExerciseDisplay.ExerciseName=#Exercise", conn)
It's showing up an error from the syntax. Can this be achieved?

How to use LAST_INSERT_ID() in c# windows form?

In database I have three tables-
patient(patientID,fName,lName)
illness(diseaseID,diseaseName)
patientDisease(patientID, diseaseID, dateChecked)
patientID and diseaseID are index.
So on in c# I have three textboxes fNameTxt and lNameTXT, diseaseTxt.I want to store the name in patient table and disease name in illness table. Besides, I have to record patientID and diseaseID in patientDisease table as well. For patient table, I used following code. I knew, I can use
SET #variable = LAST_INSERT_ID()
to get the id, but realised c#(visual studio) doesnt recognize it. Basically, I couldnt make the overall statement. Could anybody help me to get through this condition please.
string connStr = #"server=localhost; DATABASE=mario;User ID=root;Password=;";
MySqlConnection conn1 = new MySqlConnection();
conn1.ConnectionString = connStr;
MySqlCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO patient(patientID,fName, lName)"
+ "Values("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');";
conn1.Open();
cmd.ExecuteNonQuery();
I searched some other questions here, but they are almost about suggesting the use of LAST_INSERT_ID() but not how to use it.
It will be much better if you use stored procedures
INSERT INTO patient (patientID,patientID,lName)
VALUES("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');
SET #last_id_in_patient = LAST_INSERT_ID();
INSERT INTO patientDisease (patientID,diseaseID,dateChecked)
VALUES( #last_id_in_patient ,NULL,'text'); # use ID in second table";
Now You can update your PatientDisease table for particular PatientId.
You can use this to get the last inserted id:
"SELECT * FROMtable(column) WHERE id = last_insert_id();
And use this if you want to insert a last id:
"INSERT INTO table(column) VALUES (LAST_INSERT_ID())";
Hope this might be useful.

Insert SQL Values Into a Database Table

I am getting the following error
syntax not correct near item number
but I don't see anything wrong, the values being inserted are from a dataset containing field names in variables from another sql query that is being looped through and then inserted into another table like so....
string strOrderDetails =
"INSERT INTO Orders (Order Number, Item Number, Description, Price) " +
"VALUES ('" + strOrderNo.Replace("'", "''").ToString() + "', '"
+ intItemNo + "', '"
+ strDesc.Replace("'", "''").ToString() + "', '"
+ decPrice + "')";
On execution of the above is where the code falls over and states there's an error near the word item number?
Do I need to do something to the intItemNo as it's an integer?
When a column contains spaces you need to enclose it in square brackets or other delimiter for the choosen database
But said that, please do not use string concatenation to build sql commands, but always a parameterized query.
string strOrderDetails = "INSERT INTO Orders ([Order Number], [Item Number]," +
"Description, Price) VALUES (#ordNum, #temNo, #desc, #price";
using(SqlConnection cn = new SqlConnection(conString))
using(SqlCommand cmd = new SqlCommand(strOrderDetails, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ordNum",strOrderNo);
cmd.Parameters.AddWithValue("#itemNo",intItemNo);
cmd.Parameters.AddWithValue("#desc",strDesc);
cmd.Parameters.AddWithValue("#price", decPrice);
cmd.ExecuteNonQuery();
}
As you could notice, using parameters remove the need to write code to handle quotes in the input values, but also remove the possibility of Sql Injection attacks

Problem with a sql statement

string insertCommand =
"INSERT INTO Users (UserID) VALUES" + "" + "(CONVERT(uniqueidentifier, '" +
UsersIdentityToinsert + "'),'"+ userName+",0,null')";
it tells me:
There are fewer columns in the INSERT statement than values specified
in the VALUES clause. The number of
values in the VALUES clause must match
the number of columns specified in the
INSERT statement.
But i have four columns?
you only have UserID in the insert list but in the value list, you have two values - a uniqueidentifier and a username
this would work better: (assuming the name of your username column)
string insertCommand =
"INSERT INTO Users (UserID, username) VALUES" + "" +
"(CONVERT(uniqueidentifier, '" + UsersIdentityToinsert + "'),'"+ userName+"')";
EDIT:
I feel i need to address this part a bit more clearly:
But i have four columns?
The error you received refers to the number of columns specified in the INSERT statement - not the actual table so if you start an INSERT with:
INSERT INTO AnyTable (ColumnA, ColumnB)
you need to match the number of columns here in your VALUES clause
VALUES ("Value1", "Value2")
You are missing "UserName" in column Names, that is, Column Name and values mismathch.
string insertCommand =
"INSERT INTO Users (UserID,UserName) VALUES" + "" +
"(CONVERT(uniqueidentifier, '" + UsersIdentityToinsert + "'),'"+ userName+"')";

Categories