I created a Class name EmployeeDAta write this code here and i want to Insert Radiobutton value in SQL Database
public static void AddEmployee(Employee employee)
{
string connString = ConfigurationManager.ConnectionStrings["Employee"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
using (conn)
{
SqlCommand cmd = new SqlCommand("ADDEMPLOYEE", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50).Value = employee.Name;
cmd.Parameters.Add("#FName", SqlDbType.NVarChar, 50).Value = employee.Fname;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 50).Value = employee.Address;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = employee.Email;
cmd.Parameters.Add("#Mobile", SqlDbType.NVarChar, 50).Value = employee.Mobile;
cmd.Parameters.Add("#Pincode", SqlDbType.NVarChar, 50).Value = employee.Pincode;
cmd.Parameters.AddWithValue("#VB", SqlDbType.Bit).Value = employee.VB;
cmd.Parameters.AddWithValue("#ASP", SqlDbType.Bit).Value = employee.ASP;
cmd.Parameters.AddWithValue("#Gender", SqlDbType.Int).Value = employee.Gender;
conn.Open();
cmd.ExecuteNonQuery();
}
}
add a parameter to your stored procedure call:
cmd.Parameters.AddWithValue("#ValueOfRadioButtonr", SqlDbType.Int).Value = MyRadioButton.Value;
In the stored procedure on the database, make sure you handle the extra parameter.
Related
I have a listview which is adding some products in the database. If i insert one product, it works perfectly. The problem with this code is the cmd2.Parameters.Clear(); If i insert more than one product in the form listview, it only sends the last one to the database. How can i do to insert all products, because it seems that if i don't use parameters.clear, it's not working at all. There is no error thrown, it just does not insert products.
This is the code:
private void InsertOrder_Click(object sender, EventArgs e)
{
//---------------Inserare client--------------------
SqlCommand cmd = new SqlCommand("InsertClients", con);
cmd.CommandType = CommandType.StoredProcedure;
if (TextBoxClientNou.Enabled)
{
cmd.Parameters.AddWithValue("#NumeClient", TextBoxClientNou.Text);
}
else
{
cmd.Parameters.AddWithValue("#NumeClient", ClientExistent.Text);
}
var IDClientParameter = cmd.Parameters.Add("#IDClient", SqlDbType.Int);
IDClientParameter.Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
var IDClient = (int)IDClientParameter.Value;
con.Close();
//--------------------Inserare Produse------------------
SqlCommand cmd2 = new SqlCommand("InsertProducts", con);
cmd2.CommandType = CommandType.StoredProcedure;
foreach (ListViewItem item in ListaProduse.Items)
{
cmd2.Parameters.Clear(); //Problem here
cmd2.Parameters.AddWithValue("#Denumire", item.Text);
cmd2.Parameters.AddWithValue("#Cantitate", item.SubItems[1].Text);
cmd2.Parameters.AddWithValue("#Dimensiuni", item.SubItems[1].Text);
cmd2.Parameters.AddWithValue("#Comentarii", item.SubItems[1].Text);
}
var IDProductParameter = cmd2.Parameters.Add("#IDProdus", SqlDbType.Int);
IDProductParameter.Direction = ParameterDirection.Output;
con.Open();
cmd2.ExecuteNonQuery();
var IDProdus = (int)IDProductParameter.Value;
con.Close();
//--------------------Inserare comanda-------------------
SqlCommand cmd3 = new SqlCommand("InsertOrders", con);
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.Parameters.AddWithValue("#IDClient", IDClient);
cmd3.Parameters.AddWithValue("#IDProdus", IDProdus);
cmd3.Parameters.AddWithValue("#DataInceput", dateTimePicker1.Text);
cmd3.Parameters.AddWithValue("#DataSfarsit", dateTimePicker2.Text);
cmd3.Parameters.AddWithValue("#Facturata", factstatus);
cmd3.Parameters.AddWithValue("#Livrata", livstatus);
con.Open();
cmd3.ExecuteNonQuery();
con.Close();
you have to execute the query inside your loop, cause you're adding parameters in the loop (if two ListViewItem so 8 parameters), that's why you're getting this error.
foreach (ListViewItem item in ListaProduse.Items)
{
SqlCommand cmd2 = new SqlCommand("InsertProducts", con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#DenProd", item.Text);
cmd2.Parameters.AddWithValue("#ProdQuant", item.SubItems[1].Text);
cmd2.Parameters.AddWithValue("#ProdSize", item.SubItems[1].Text);
cmd2.Parameters.AddWithValue("#ProdComm", item.SubItems[1].Text);
var IDProductParameter = cmd2.Parameters.Add("#ProdID", SqlDbType.Int);
IDProductParameter.Direction = ParameterDirection.Output;
con.Open();
cmd2.ExecuteNonQuery();
var IDProdus = (int)IDProductParameter.Value;
con.Close();
}
You are adding the parameters without clearing the originals. You can either use Parameters.Clear() or you can change the Value of existing parameters. You then need to execute the command within the loop.
Note that you must use using blocks to dispose the connection. And if you do so, the connection will be closed automatically
Specify the parameter types and lengths explicitly
var listIds = new List<int>();
using (var con = new SqlConnection(YourConnString))
using (var cmd2 = new SqlCommand("InsertProducts", con) { CommandType = CommandType.StoredProcedure })
using (var cmd3 = new SqlCommand("InsertOrders", con) { CommandType = CommandType.StoredProcedure })
{
cmd2.Parameters.Add("#DenProd", SqlDbType.NVarChar, 50);
cmd2.Parameters.Add("#ProdQuant", SqlDbType.NVarChar, 50);
cmd2.Parameters.Add("#ProdSize", SqlDbType.NVarChar, 50);
cmd2.Parameters.Add("#ProdComm", SqlDbType.NVarChar, 50);
var IDProductParameter = cmd2.Parameters.Add("#ProdID", SqlDbType.Int);
IDProductParameter.Direction = ParameterDirection.Output;
cmd3.Parameters.Add("#IDClient", SqlDbType.Int).Value = IDClient;
cmd3.Parameters.Add("#IDProdus", SqlDbType.Int);
cmd3.Parameters.Add("#DataInceput", SqlDbType.DateTime).Value = dateTimePicker1.Text;
cmd3.Parameters.Add("#DataSfarsit", SqlDbType.DateTime).Value = dateTimePicker2.Text;
cmd3.Parameters.Add("#Facturata", SqlDbType.NVarChar, 50).Value = factstatus;
cmd3.Parameters.Add("#Livrata", SqlDbType.NVarChar, 50).Value = livstatus;
con.Open();
foreach (ListViewItem item in ListaProduse.Items)
{
cmd2.Parameters["#DenProd"].Value = item.Text;
cmd2.Parameters["#ProdQuant"].Value = item.SubItems[1].Text;
cmd2.Parameters["#ProdSize"].Value = item.SubItems[1].Text;
cmd2.Parameters["#ProdComm"].Value = item.SubItems[1].Text;
cmd2.ExecuteNonQuery();
var IDProdus = (int)IDProductParameter.Value; // do something with this value
cmd3.Parameters.AddWithValue("#IDProdus", IDProdus);
cmd3.ExecuteNonQuery();
}
}
I must say, ideally you should use either a Table Valued parameter or SqlBulkCopy to do this in bulk, it will not be performant for large numbers of rows.
it always show an error Incorrect syntax near ')'.
I didnt see any wrong inputs
See my code below
byte[] content = ImageToStream(fName);
cnn.Open();
string sql = "update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id)";
SqlCommand cmd1 = new SqlCommand(sql, cnn);
cmd1.Parameters.AddWithValue("#pic", SqlDbType.Image).Value = content;
cmd1.Parameters.AddWithValue("#fname", SqlDbType.VarChar).Value = txtfirstname.Text;
cmd1.Parameters.AddWithValue("#mname", SqlDbType.VarChar).Value = textBox1.Text;
cmd1.Parameters.AddWithValue("#lname", SqlDbType.VarChar).Value = txtlastname.Text;
cmd1.Parameters.AddWithValue("#position", SqlDbType.VarChar).Value = comboBox2.Text;
cmd1.Parameters.AddWithValue("#startterm", SqlDbType.DateTime).Value = dateTimePicker2.Value.Date;
cmd1.Parameters.AddWithValue("#endterm", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
cmd1.Parameters.AddWithValue("#id", SqlDbType.Int).Value = int.Parse(ID.Text);
cmd1.ExecuteNonQuery();
cnn.Close();
MessageBox.Show("successfully updated");
dataGridView1.DataSource = db.sp_viewofficials();
it should save to sql server my save works
Your update statement has extra ending bracket which is not needed.
"update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id"
I'm creating a page that inserts user information into a SQL server. I want to check to make sure that the database table doesn't already have the user EDIPI number in it and if it does not than it insert the new provided information. My error message is:
Procedure or function 'TestTableInsert' expects parameter '#EDIPI', which was not supplied.
My btnSaveSP_Click should allow the user to insert the information in to the database but I believe my Stored Procedure is wrong.
My Button Code:
protected void btnSaveSP_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand();
SqlCommand sqlCmd = new SqlCommand("TestTableInsert", sqlconn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlcomm.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlcomm.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
sqlCmd.ExecuteNonQuery();
sqlconn.Close();
}
My Stored Procedure code:
ALTER PROCEDURE [dbo].[TestTableInsert]
#EDIPI nvarchar(50),
#First nvarchar(50)
AS
BEGIN
IF NOT EXISTS (SELECT * FROM TestTable where EDIPI = #EDIPI)
BEGIN
INSERT INTO TestTable (EDIPI,First)
VALUES (#EDIPI, #First)
END
END
You need to change
sqlcomm.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlcomm.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
into
sqlCmd.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlCmd.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
Note that in the first you use sqlcomm while it should be sqlCmd
I have a database made up of 2 (more, actually, but only 2 im working with) tables.
The Material table consists solely of the material-number and the description
DPMatNr
DPBezeichnung
The Eigenschaften table is there to hold the properties of the materials.
It uses the columns:
EigenschaftenBezeichnerID
Wert (value)
My problem is: each entry in the Material table needs to have multiple entries in the Eigenschaften table.
For example:
"Material":
DPMatNr = 001,
DPBezeichnung = "Description"
"Eigenschaften":
EigenschaftenBezeichnerID = 1,
Wert = "A4"
EigenschaftenBezeichnerID = 3,
Wert = "80" and so on.
My code currently looks like this:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string query = #"Insert INTO dbo.Material (DPMatNr, DPBezeichnung)
VALUES (#matnummer, #bezeichnung)";
string query2 = #"Insert INTO dbo.Eigenschaften
(EigenschaftenBezeichnerID, Wert)
VALUES (#1, #format, #2, #grammatur, #3, #gewicht,
#4, #eform, #5, #kuvertierung,
#6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cn.Open();
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}
Now I currently get an error that says:
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Material' with unique index 'IX_MatNrUnique'
What am I doing wrong?
The Problem here is, that for every "Eigenschaft" you insert into the table you also try to create an entry in the "Material" table. But since every material should only be inserted once (therefore the primary key) you get the error.
Edit:
You could adjust your method like the following:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string check = "Select COUNT(*) FROM dbo.Material where DPMatNr = #matnummer";
string query = "Insert INTO dbo.Material (DPMatNr, DPBezeichnung)" + "VALUES (#matnummer, #bezeichnung)";
string query2 = "Insert INTO dbo.Eigenschaften (EigenschaftenBezeichnerID, Wert)" + "VALUES (#1, #format, #2, #grammatur, #3, #gewicht, #4, #eform, #5, #kuvertierung, #6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand chkCom = new SqlCommand(check, cn))
{
cn.Open();
chkCom.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
int? matCnt = chkCom.ExecuteScalar() as int?;
if (matCnt == 0 || matCnt == null)
{
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cmd.ExecuteNonQuery();
}
}
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}
I have been attacked on my last few questions here for writing code that is open to injections. I am looking for honest help to make sure I am finally doing this the safest and correct way. Please give me any tips to make this as secure as possible.
using (SqlConnection conn = new SqlConnection(""))
{
try
{
SqlCommand cmd = new SqlCommand(#"INSERT dbo.Table (FullName, Category, Street, City, State, Zip, PhoneDay, PhoneEven, Email, Employer, Description, UserName,
UserStreet, UserCity, UserState, UserZip, UserPhoneDay, UserPhoneEven, UserEmail, SubmitDate)
VALUES (#f1, #f2, #f3, #f4, #f5, #f6, #f7, #f8, #f9, #f10, #f11, #f12, #f13, #f14, #f15, #f16, #f17, #f18, #f19, #f20)", conn);
conn.Open();
cmd.Parameters.Add("#f1", SqlDbType.NVarChar, 100).Value = NameTxtBox.Text;
cmd.Parameters.Add("#f2", SqlDbType.NVarChar, 100).Value = HeroicList.SelectedValue;
cmd.Parameters.Add("#f3", SqlDbType.NVarChar, 100).Value = StreetTxtBox.Text;
cmd.Parameters.Add("#f4", SqlDbType.NVarChar, 100).Value = CityTxtBox.Text;
cmd.Parameters.Add("#f5", SqlDbType.NVarChar, 100).Value = StateTxtBox.Text;
cmd.Parameters.Add("#f6", SqlDbType.NVarChar, 100).Value = ZipTxtBox.Text;
cmd.Parameters.Add("#f7", SqlDbType.NVarChar, 100).Value = PhoneDayTxtBox.Text;
cmd.Parameters.Add("#f8", SqlDbType.NVarChar, 100).Value = PhoneEvenTxtBox.Text;
cmd.Parameters.Add("#f9", SqlDbType.NVarChar, 100).Value = EmailTxtBox.Text;
cmd.Parameters.Add("#f10", SqlDbType.NVarChar, 100).Value = EmpTxtBox.Text;
cmd.Parameters.Add("#f11", SqlDbType.NVarChar, 100).Value = WhyTxtBox.Text;
cmd.Parameters.Add("#f12", SqlDbType.NVarChar, 100).Value = UserNameTxtBox.Text;
cmd.Parameters.Add("#f13", SqlDbType.NVarChar, 100).Value = UserStreetTxtBox.Text;
cmd.Parameters.Add("#f14", SqlDbType.NVarChar, 100).Value = UserCityTxtBox.Text;
cmd.Parameters.Add("#f15", SqlDbType.NVarChar, 100).Value = UserStateTxtBox.Text;
cmd.Parameters.Add("#f16", SqlDbType.NVarChar, 100).Value = UserZipTxtBox.Text;
cmd.Parameters.Add("#f17", SqlDbType.NVarChar, 100).Value = UserPhoneDayTxtBox.Text;
cmd.Parameters.Add("#f18", SqlDbType.NVarChar, 100).Value = UserPhoneEvenTxtBox.Text;
cmd.Parameters.Add("#f19", SqlDbType.NVarChar, 100).Value = UserEmailTxtBox.Text;
cmd.Parameters.Add("#f20", SqlDbType.DateTime).Value = DateTime.Now.ToString();
cmd.ExecuteNonQuery();
messageLabel.Text = "Your submission has been sent!";
messageLabel.Visible = true;
}
catch (System.Data.SqlClient.SqlException ex)
{
messageLabel.Text = ex.Message;
messageLabel.Visible = true;
}
}
You're protected with respect to insertion, yes. Using your code, it doesn't matter what the user puts in any of the textboxes (or what they put in any other sort of response they can cook up) nothing will happen beyond their data being stuck into fields of a new row of the given table, exactly as the strings were given to you.
The only way (that comes to mind) that someone could maliciously inject code would depend on how you use the data once it's in the database. If you go and, for example, take a field from this table and stick it in a LiteralControl without escaping anything and show it to other users then someone could stick in nasty JavaScript code that they run on another person's machine, for example. That would be a "cross site scripting" attack. To prevent that you need to make sure that any user-inputted data is sanitized before being displayed.