How to insert data into SQL Server? - c#

I have code like this:
con.Open();
cmd = new SqlCommand("insert into Penawaran (ID_Paket,Jenis_Paket,Harga_Paket) Values (#ID_Paket,#Jenis_Paket,#Harga_Paket", con);
cmd.Parameters.AddWithValue("#ID_Paket", txtIDPaket.Text);
cmd.Parameters.AddWithValue("#Jenis_Paket", txtjenisPaket.Text);
cmd.Parameters.AddWithValue("#Harga_Paket", txtHargaPaket.Value); // this is int sir how to insert it, still error i write like this
cmd.ExecuteNonQuery();
con.Close();
Please help me to inside int to my table Paket.

There is a missing parenthesis at the end of Insert query
INSERT INTO Penawaran (ID_Paket,Jenis_Paket,Harga_Paket)
VALUES (#ID_Paket,#Jenis_Paket,#Harga_Paket) --Here

Try this
SqlConnection con = new SqlConnection();
con.Open();
SqlCommand cmd = new SqlCommand("insert into Penawaran (ID_Paket,Jenis_Paket,Harga_Paket) Values (#ID_Paket,#Jenis_Paket,#Harga_Paket", con));
cmd.Parameters.Add("#ID_Paket", SqlDbType.Int);
cmd.Parameters.Add("#Jenis_Paket", SqlDbType.VarChar);
cmd.Parameters.Add("#Harga_Paket", SqlDbType.VarChar); // this is int sir how to insert it, still error i write like this
cmd.Parameters["#ID_Paket"] = int.Parse(txtIDPaket.Text);
cmd.Parameters["#Jenis_Paket"] = txtjenisPaket.Text;
cmd.Parameters["#Harga_Paket"] = txtHargaPaket.Value; // this is int sir how to insert it, still error i write like this
cmd.ExecuteNonQuery();
con.Close();

Related

How to get table_ID(PK) of last inserted row using asp and sql

I am trying to get value of last inserted row using following piece of code. I know ##IDENTITY and IDENTITY_SCOPE but how to use them when i am writing code in asp parametric query.
SqlConnection MySQL = new SqlConnection(ConfigurationManager.ConnectionStrings["BloodDonorRegistrationConnectionString"].ToString());
string BloodReq = "insert into Blood_Request(R_Name,R_Phone,R_Blood_Group,R_City,R_Address,Date,Time) values (#Name,#cell,#BGroup,#City,#Address,#date,#time)";
SqlCommand Cmd = new SqlCommand(BloodReq, MySQL);
Cmd.Parameters.AddWithValue("#Name", TextBoxName.Text);
Cmd.Parameters.AddWithValue("#cell", TextBoxPhone.Text);
Cmd.Parameters.AddWithValue("#BGroup", dropbownBlood.SelectedItem.Text);
Cmd.Parameters.AddWithValue("#City", DropDownListCity.SelectedItem.Text);
Cmd.Parameters.AddWithValue("#Address", TextBoxLocation.Text);
Cmd.Parameters.AddWithValue("#date", DateTime.Now.Date);
Cmd.Parameters.AddWithValue("#time", DateTime.Now.TimeOfDay);
MySQL.Open();
Cmd.ExecuteNonQuery();
MySQL.Close();
Please Help and thanks in advance.
Use cmd.ExecuteScalar instead of Cmd.ExecuteNonQuery(). You can also use ExecuteReader if you want to return more values.
And in your Sql use OUTPUT INSERTED.ID as in
string BloodReq = "insert into Blood_Request(R_Name,R_Phone,R_Blood_Group,R_City,R_Address,Date,Time)
OUTPUT INSERTED.ID
values (#Name,#cell,#BGroup,#City,#Address,#date,#time)"
Use scope_identity, a full working example based upon your code would be:
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["BloodDonorRegistrationConnectionString"].ToString())) {
int insertedID;
var cmd = "insert into Blood_Request(R_Name,R_Phone,R_Blood_Group,R_City,R_Address,Date,Time) values (#Name,#cell,#BGroup,#City,#Address,#date,#time);SELECT CAST(scope_identity() AS int)";
using (var insertCommand = new SqlCommand(cmd, con)) {
insertCommand.Parameters.AddWithValue("#Name", TextBoxName.Text);
insertCommand.Parameters.AddWithValue("#cell", TextBoxPhone.Text);
insertCommand.Parameters.AddWithValue("#BGroup", dropbownBlood.SelectedItem.Text);
insertCommand.Parameters.AddWithValue("#City", DropDownListCity.SelectedItem.Text);
insertCommand.Parameters.AddWithValue("#Address", TextBoxLocation.Text);
insertCommand.Parameters.AddWithValue("#date", DateTime.Now.Date);
insertCommand.Parameters.AddWithValue("#time", DateTime.Now.TimeOfDay);
con.Open();
insertedID = (int)insertCommand.ExecuteScalar();
}
}
...
string BloodReq = "insert into Blood_Request(R_Name,R_Phone,R_Blood_Group,R_City,R_Address,Date,Time) values (#Name,#cell,#BGroup,#City,#Address,#date,#time); SELECT SCOPE_IDENTITY() AS IID";
...
var insertedID = (Int32)Cmd.ExecuteScalar();

Incrementing an int during insert

I'm trying to increment an integer in an MS Access table from a c# .net page during insert.
I'm getting a syntax error when attempting the following. Also unsure if I should be using an ExecuteNonQuery() or not?
OleDbCommand cmd = new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget)", conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
You miss a bracket after tblTarget:
OleDbCommand cmd =
new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))", conn);
Here is a little review of your code, try using the using pattern:
using(var conn = new Connection())
{
conn.Open();
string sql = "INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}
You're missing a bracket, try:
INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))
But I think you are going to have other issues, you need something closer to this:
INSERT INTO tblTarget ( target, ref )
SELECT #target AS Targ, First((SELECT MAX(ref)+1 FROM tblTarget)) AS MaxRef
FROM tblTarget
GROUP BY #target;
The correct way to achieve your goal is
string sql = "INSERT INTO tblTarget (target,ref) " +
"SELECT ?, MAX(ref)+1 FROM tblTarget";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
I would not do the increment by the sql or code, we can use AutoNumber data type for auto increase the value in access.
string sql = "INSERT INTO tblTarget(target) VALUES(#target)";
using(var conn = new Connection())
using(OleDbCommand cmd = new OleDbCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}

Accessing SQL Server stored procedure output parameter in C#

I have a simple SQL Server stored procedure:
ALTER PROCEDURE GetRowCount
(
#count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET #count=##ROWCOUNT;
RETURN
I am trying to access the output parameter in the following C# code:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "GetRowCount";
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
SqlDataReader reader=cmd.ExecuteReader();
int ans = (int)cmd.Parameters["#count"].Value;
Console.WriteLine(ans);
But on running the code, a NullReferenceException is being thrown at the second last line of the code. Where am I going wrong? Thanks in advance!
P.S. I am new to SQL Procedures, so I referred this article.
I'd suggest you put your SqlConnection and SqlCommand into using blocks so that their proper disposal is guaranteed.
Also, if I'm not mistaken, the output parameters are only available after you've completely read the resulting data set that's being returned.
Since you don't seem to need that at all - why not just use .ExecuteNonQuery() instead? Does that fix the problem?
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("dbo.GetRowCount", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery(); // *** since you don't need the returned data - just call ExecuteNonQuery
int ans = (int)cmd.Parameters["#count"].Value;
con.Close();
Console.WriteLine(ans);
}
Also : since it seems you're only really interested in the row count - why not simplify your stored procedure to something like this:
ALTER PROCEDURE GetRowCount
AS
SELECT COUNT(*) FROM Emp WHERE age > 30;
and then use this snippet in your C# code:
con.Open();
object result = cmd.ExecuteScalar();
if(result != null)
{
int ans = Convert.ToInt32(result);
}
con.Close();
you have to specify that it is a stored procedure not a query
cmd.CommandType = CommandType.StoredProcedure;
Just use ExecuteNonQuery , you can't use ExecuteReader with out parameter in this case
cmd.ExecuteNonQuery();
Or if you want try with ExecuteScalar and ReturnValue
You should add
cmd.CommandType = CommandType.StoredProcedure
before calling it
I find the problem, its the connection string.
But now, in the code:
usuary = (string)cmd.Parameters["#USUARIO"].Value;
password = (string)cmd.Parameters["#CLAVE"].Value;
the compiler infomrs thats values are null...

What is the cause of "database table definition wrong" error

This is my first step to programming.guys your help hands required.I watched youtube video & write small program,the exact way he written..he doesn't have error.but i got the error.I just passed the textbox values database.(error is database table definition wrong ). In my table i use for this field is BBMgrID nvarchar(50) NOT NULL
SqlConnection con = new SqlConnection("Data Source=spilap;Initial Catalog=spiDB;User ID=sa;Password=sa123");
protected void btn_submit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into tbl_BBmgr values('" + TextBox1.Text+"')",con);
cmd.ExecuteNonQuery();
}
Try this :
SqlCommand cmd = new SqlCommand("Insert [TableName] ([ColumnName]) Values(#A)", con);
cmd.Parameters.AddWithValue("#A", TextBox1.text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Update :
SqlCommand cmd = new SqlCommand("Insert [TableName] ([Column1],[Column2],[Column3]) Values(#A,#B,#C)", con);
cmd.Parameters.AddWithValue("#A", TextBox1.text);
cmd.Parameters.AddWithValue("#B", TextBox2.text);
cmd.Parameters.AddWithValue("#C", TextBox3.text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
You should write it like this:
Insert into tbl_BBmgr (BBMgrID) values('" + TextBox1.Text+"')
If like you stated you have 5 fields in the DB table, you need to explicitly specify the column you want the value to go:
SqlCommand cmd = new SqlCommand("Insert into tbl_BBmgr (BBMgrID) values('" + TextBox1.Text+"')",con);
EDIT: Now and in the future, to ensure that you are sending the right value to the respective field, its always advisable to specify the columns in your INSERT statement in the form:
INSERT INTO Name_Of_Table ([Column1], [Column2], [Column3], ...) VALUES ([Value_For_Column1], [Value_For_Column2], [Value_For_Column3], ...)

Insert data into SQL Server from C# code

I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query

Categories