Call stored procedure with multiple parameters [duplicate] - sql-server

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# stored procedure with parameters
I am trying to call a stored procedure from c# passing in multiple parameters and can't to get it working. Here is what I have so far.
cmd = new SqlCommand();
cmd = dbConn.CreateCommand();
cmd.CommandText = "inserttoTable #size = " + size + ", #brand = " + brand + ", #manu = " + manu + ", #t= " + id.ToString();
cmd.ExecuteNonQuery();
Size, brand and manu are all strings. inserttoTable is the stored procedure.
I get the following error : System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'TO'.

check out this:
SqlCommand.Parameters Property

You'll have fewer problems if you use parameters and change the command type to stored procedure:
cmd = new SqlCommand();
cmd = dbConn.CreateCommand();
cmd.CommandText = "inserttoTable";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#size", size));
cmd.Parameters.Add(new SqlParameter("#brand", brand));
cmd.Parameters.Add(new SqlParameter("#manu", manu));
cmd.Parameters.Add(new SqlParameter("#t", id.ToString()));
cmd.ExecuteNonQuery();

Although this is not the best method to call a stored procedure, if you add single quotes around the string parameters, you should be fine.
cmd = new SqlCommand();
cmd = dbConn.CreateCommand();
cmd.CommandText = "inserttoTable #size = '" + size + "', #brand = '" + brand + "', #manu = '" + manu + "', #t= '" + id.ToString() + "'";
cmd.ExecuteNonQuery();
This code is very dated and was already deprecated 10 years ago.

Related

SQL Exception in run time [duplicate]

This question already has answers here:
Why do we always prefer using parameters in SQL statements?
(7 answers)
How to give ADO.NET Parameters
(4 answers)
Closed 5 months ago.
I am trying to add values to a database using WPF form.
This is my code:
private void Insertbtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=DESKTOP-HSIK0SQ; Initial Catalog=Demo; Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Student VALUES ("+ RollNumebrtxt + "," + FNametxt + "," + Coursetxt + ")";
int count = cmd.ExecuteNonQuery();
MessageBox.Show(count + " record saved successfully");
conn.Close();
}
When I am hitting the insert button:
This is the exception being thrown:
I am sure that whichever the labels and text boxes I have added they have unique name in the property. It is throwing exception while executing the query command
I am not sure what I could miss here?
Make sure to surround these values with single quotes '', and if these variables are the TextBoxes, then you have to call .Text on them to get the proper values..
cmd.CommandText = "Insert into Student values ('"+ RollNumebrtxt.Text + "','" + FNametxt.Text + "','" +
Coursetxt.Text + "');";
Better to parametrised your query..
Replace
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Student VALUES ("+ RollNumebrtxt + "," + FNametxt + "," + Coursetxt + ")";
With
SqlCommand cmd = new SqlCommand("INSERT INTO Student VALUES(#RollNumber, #FName, #CourseName)", conn);
cmd.Parameters.Add("#RollNumber", SqlDbType.Int).Value = int.Parse(RollNumebrtxt.Text);
cmd.Parameters.Add("#FName", SqlDbType.VarChar, 100).Value = FNametxt.Text;
cmd.Parameters.Add("#CourseName", SqlDbType.VarChar, 100).Value = Coursetxt.Text;

Must declare scalar variable in If Exist SQL record in vb.net

I need help with the code below. Whenever I run the code, I get this error:
Must declare the scalar variable "#1"
Must declare the scalar variable "#2"
What is missing?
con = New SqlConnection(cs)
con.Open()
Dim cb1 As String = "if exists (select Fedo from Mimos where Fedo=#1)" + "BEGIN " + "Update Mimos Set ActivationID=#2,Date=#3 where Fedo=#1)" + "END" + "Else" + "insert into Mimos (Fedo,ActivationID,Date) VALUES (#d1,#d2,#d3)"
cmd = New SqlCommand(cb1)
cmd.Connection = con
cmd.Parameters.AddWithValue("#d1", Encrypt(TextBox1.Text.Trim))
cmd.Parameters.AddWithValue("#d2", Encrypt(TextBox2.Text.Trim()))
cmd.Parameters.AddWithValue("#d3", System.DateTime.Now)
cmd.ExecuteReader()
con.Close()
Type with #d1, #d2 and #d3
con = New SqlConnection(cs)
con.Open()
Dim cb1 As String = "if exists (select Fedo from Mimos where Fedo=#d1)" + "BEGIN " + "Update Mimos Set ActivationID=#d2,Date=#d3 where Fedo=#d1)" + "END" + "Else" + "insert into Mimos (Fedo,ActivationID,Date) VALUES (#d1,#d2,#d3)"
cmd = New SqlCommand(cb1)
cmd.Connection = con
cmd.Parameters.AddWithValue("#d1", Encrypt(TextBox1.Text.Trim))
cmd.Parameters.AddWithValue("#d2", Encrypt(TextBox2.Text.Trim()))
cmd.Parameters.AddWithValue("#d3", System.DateTime.Now)
cmd.ExecuteReader()
con.Close()

How do I insert value into dataset at runtime using microsoft SQL server in vb.net

this is the code I am using for trying to insert a row to my dataset.
It executes properly till sqlConnection is opened. But the nonQuery execution throws a 'System.Data.SqlClient.SqlException' I believe there is something wrong with my connection string, I copied it from the app./config file and I cannot figure out what is wrong. Also, I know I should use a parameterized SQL query, I will implement that later.
Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection("Data Source=(localdb)\MSSQLLocalD;Initial Catalog=ContactInfo;Integrated Security=True;Pooling=False")
Dim cmd As New SqlClient.SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO Table (ID, FirstName, MiddleName, LastName, Type, Telephone, Extension, Email) VALUES (" + row.ID.ToString + "," + "'" + row.FirstName + "'" + "," + "'" + row.MiddleName + "'" + "," + "'" + row.LastName + "'" + "," + "'" + row.Type + "'" + "," + row.Telephone.ToString + "," + "'" + row.Extension + "'" + "," + "'" + row.Email + "')"
cmd.Connection = sqlConnection1
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
First, Don't think that you can name your table "Table" so change it to your real table name and it should run
And USE SQL PARAMETERS!
Second, get the result of ExecuteNonQuery to a variable so you can check, if a record was written or not.

Can I use SQLCLR stored procedure to update a column of a database table

I wanted to update the values of a few columns of a database table, using queries or stored procedure, but wanted to use my C# library to alter the value.
For ex, I want the columns A,B,C of table T to be replaced with Encrypt(A), Encrypt(B) and Encrypt(C) where Encrypt is a part of a C# library.
I could have done it in a simple console application, but I have to do this process for a lot of columns in lot of tables. Could I use some SQLCLR stored procedure/query to do this process in SQL Server Management Studio?
It will be really great if someone could assist in this.
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction()]
public static void Enc()
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
SqlCommand command;
SqlCommand command1;
for (int i = 0; i < 1; i++)
{
command = new SqlCommand("SELECT " + tableFieldArray[i, 1].ToString() + " FROM " + tableFieldArray[i, 0].ToString(), connection);
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
while (reader.Read())
{
if (!reader.IsDBNull(0) && !String.IsNullOrEmpty(reader.GetString(0)))
{
//SqlContext.Pipe.Send("Data = " + reader.GetString(0) + "; Encrypted = " + Encrypt(reader.GetString(0)));
SqlContext.Pipe.Send("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'");
//query = "UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
// + tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
// + "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'";
command1 = new SqlCommand("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'",connection);
}
}
}
SqlCommand command1 = new SqlCommand(query , connection);
command1.ExecuteNonQuery();
}
connection.Close();
}
}
public static string Encrypt(string TextFromForm)
{
//implementation
}
}
}
For some reason this question is a complete duplicate of ( Can I use SQLCLR stored procedure to update a column of a database table ( using some compiled dll) ), but assuming that other one will be closed (it should be), my answer is the same:
You can use SQLCLR to call encryption from C#, though this is the wrong approach. If you need to do a custom algorithm, you should encapsulate that into a SQLCLR function so that it can be used in an UPDATE statement or even an INSERT or SELECT or anywhere. Something like:
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true)]
public static SqlString EncryptByAES(SqlString TextToEncrypt)
{
return DoSomething(TextToEncrypt.Value);
}
}
Then you can use that function as follows:
UPDATE tb
SET tb.FieldA = EncryptByAES(tb.FieldA)
FROM dbo.TableName tb
WHERE tb.FieldA some_test_to_determine_that_FieldA_is_not_alreay_encrypted;
BUT, before you write a custom encryption algorithm, you might want to check out the several built-in paired ENCRYPTBY / DECRYPTBY functions that might do exactly what you need:
ENCRYPTBYASYMKEY / DECRYPTBYASYMKEY
ENCRYPTBYCERT / DECRYPTBYCERT
ENCRYPTBYKEY / DECRYPTBYKEY
ENCRYPTBYPASSPHRASE / DECRYPTBYPASSPHRASE

Syntax error in INSERT INTO statement

I have a problem when i m connection with access database then i m getting a error Syntax error in INSERT INTO statement. and my code is :
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/Database2.accdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "insert into data (FirstName,Email,Password,Address) values ('" +
txt_fstname.Text + "','" + txt_email.Text + "', '" +
txt_pass.Text + "', '" + txt_add.Text + "')";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("Default.aspx");
plz suggest me.
"Thanks"
Password is a reserved word in Jet/ACE SQL so you must enclose it in square brackets:
string query = "insert into data (FirstName,Email,[Password],Address) values ('" +

Resources