Oledb update sql statement example - sql

con.Open();
cmd = new OleDbCommand("UPDATE staff SET StaffNr = #a, FirstName = #b,
Surname = #c, Email = #d, Balance = #e WHERE Email = #d", con);
cmd.Parameters.AddWithValue("#b", textBoxStaffName.Text);
cmd.Parameters.AddWithValue("#c", textBoxStaffSur.Text);
cmd.Parameters.AddWithValue("#d", textBoxStaffE.Text);
cmd.Parameters.AddWithValue("#e", double.Parse(textBoxSatffBal.Text));
cmd.Parameters.AddWithValue("#a", int.Parse(textBoxStaffNr.Text));
cmd.ExecuteNonQuery();
con.Close();
not updating the database for some reason but the code runs

OldDb uses ? for parameters, not #x. You have to add parameters in order. The name is ignored in AddWithValue (this method comes from a general purpose superclass)
con.Open();
cmd = new OleDbCommand("Update staff set StaffNr = ?, FirstName = ?,
Surname = ?, Balance = ? Where Email = ?", con);
cmd.Parameters.AddWithValue("#a", int.Parse(textBoxStaffNr.Text));
cmd.Parameters.AddWithValue("#b", textBoxStaffName.Text);
cmd.Parameters.AddWithValue("#c", textBoxStaffSur.Text);
cmd.Parameters.AddWithValue("#e", double.Parse(textBoxSatffBal.Text));
cmd.Parameters.AddWithValue("#d", textBoxStaffE.Text);
cmd.ExecuteNonQuery();
con.Close();

Related

Insert data into 2 related tables at once?

I am trying to insert into two tables at once using the primary key from the first table to insert into the second but I am not sure how to go about it.
My table structure is as follows:
Person
PersonId
FirstName
Surname
Employee
EmployeeId
HoursWorked
PersonId in the Person table is an auto incremented column. EmployeeId in the second table is a primary and foreign key that should be the same as PersonId.
I been trying with this query string which I found on Google but with not much luck:
string queryString = "BEGIN TRANSACTION DECLARE #DataID int; "
+"INSERT INTO Person(FirstName, Surname) VALUES(#firstName, #surname);"
+ "SELECT #DataID = scope_identity();"
+ "INSERT INTO Employee VALUES(#DataId, #hoursWorked);"
+ "COMMIT";
From C#, you can try something like this:
// define the INSERT query - insert a firstname,surname into "Person",
// and insert a row into the Emplyoee table with the new ID
// created by the first insert
string insertStmt = #"BEGIN TRANSACTION
INSERT INTO dbo.Person(FirstName, Surname) VALUES(#FirstName, #Surname);
DECLARE #NewPersonId INT = SCOPE_IDENTITY();
INSERT INTO dbo.Employee(EmployeeId, HoursWorked) VALUES(#NewPersonId, #HoursWorked);
COMMIT TRANSACTION;"
// define connection and command for inserting data
using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand cmdInsert = new SqlCommand(insertStmt, conn))
{
// Define parameters - adapt datatype and max length as required
cmdInsert.Parameters.Add("#FirstName", SqlDbType.VarChar, 100);
cmdInsert.Parameters.Add("#Surname", SqlDbType.VarChar, 100);
cmdInsert.Parameters.Add("#HoursWorked", SqlDbType.Int);
// set parameter values
cmdInsert.Parameters["#FirstName"].Value = "John";
cmdInsert.Parameters["#Surname"].Value = "Doe";
cmdInsert.Parameters["#HoursWorked"].Value = 35;
// Open connection, execute query, close connection
conn.Open();
int rowsInserted = cmdInsert.ExecuteNonQuery();
conn.Close();
}
Update: as mentioned by #charlieface, you can write this code more concisely IF you're only ever inserting a single row - like this:
// define connection and command for inserting data
using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand cmdInsert = new SqlCommand(insertStmt, conn))
{
// Define and set parameters
cmdInsert.Parameters.Add("#FirstName", SqlDbType.VarChar, 100).Value = "John";
cmdInsert.Parameters.Add("#Surname", SqlDbType.VarChar, 100).Value = "Doe";
cmdInsert.Parameters.Add("#HoursWorked", SqlDbType.Int).Value = 35;
// Open connection, execute query, close connection
conn.Open();
int rowsInserted = cmdInsert.ExecuteNonQuery();
conn.Close();
}
You need to specify the columns you are inserting into.
You should also use SET XACT_ABORT ON if you have an explicit transaction.
Note also the use of a multi-line string.
string queryString = #"
SET XACT_ABORT ON;
BEGIN TRANSACTION;
INSERT INTO Person (FirstName, Surname)
VALUES(#firstName, #surname);
DECLARE #DataID int = scope_identity();
INSERT INTO Employee (EmployeeId, HoursWorked)
VALUES(#DataId, #hoursWorked);
COMMIT;
";

SQL Dynamic Query - Incorrect syntax near '#WhereClause'

//_whereclause is: where (lastName like '%Davis%')
public static MyList GetAll(string _whereclause)
{
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
string selectSQL = "";
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable]";
if (_whereclause != string.Empty)
{
selectSQL += " #WhereClause";
}
using (SqlCommand myCommand = new SqlCommand(selectSQL, myConnection))
{
myCommand.CommandType = CommandType.Text;
SqlParameter whereClauseParam = new SqlParameter("#WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause;
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{..............
If I run it with the #WhereClause I get error:
Incorrect syntax near '#WhereClause'.
Your select query should be like
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable] where (lastName like '%" + #WhereClause + "%')";
Assuming that:
SqlParameter whereClauseParam = new SqlParameter("#WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause; //Here you are getting the value as 'Davis'
But in case you are getting the value in it as where (lastName like '%Davis%') then you simply need to add a space after
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable] ";
^^ here

"Procedure or function 'UPDATE' expects parameter '#Id', which was not supplied" in Windows Form

We created a Windows Form to update a table in SQL Server.
First I click Enter ID to retrieve details from database, then after changing some data, when I click on Update button, I get an error:
Procedure or function 'UPDATE' expects parameter '#Id', which was not supplied.
Windows Form Design :
Click here
Error :
Click here
Code for Windows Form:
public partial class Update : Form
{
string connectionString = #"Data Source=AMAR;Initial Catalog=Hotel;Integrated Security=True";
public Update()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
TestObject t = null;
string spName = "Get";
//string queryText = "Select * from TestTable where Id = " +txtId.Text;
SqlConnection conn = new SqlConnection(connectionString);
//SqlCommand com = new SqlCommand(spName, conn);
SqlCommand com = new SqlCommand(spName, conn);
com.Parameters.AddWithValue("#Id", ID.Text);
com.CommandType = CommandType.StoredProcedure;
conn.Open();
using (SqlDataReader reader = com.ExecuteReader())
{
t = new TestObject();
while (reader.Read())
{
t.Id = reader["ID"].ToString();
t.Status = reader["Status"].ToString();
t.FName = reader["FirstName"].ToString();
t.LName = reader["LastName"].ToString();
t.Addr = reader["Address"].ToString();
t.City = reader["City"].ToString();
t.State = reader["State"].ToString();
t.Country = reader["Country"].ToString();
t.PhoneNo = reader["PhoneNo"].ToString();
t.Email = reader["EmailId"].ToString();
t.Pin = reader["Pincode"].ToString();
t.CheckIn = reader["CheckIn"].ToString();
t.CheckOut = reader["CheckOut"].ToString();
t.AdultNo = reader["AdultNo"].ToString();
t.ChildNo = reader["InfantNo"].ToString();
t.InfantNo = reader["InfantNo"].ToString();
t.RoomNo = reader["RoomNo"].ToString();
};
}
Statustxt.Text = t.Status;
txtfName.Text = t.FName;
txtlName.Text = t.LName;
txtAddr.Text = t.Addr;
City.Text = t.City;
State.Text = t.State;
Country.Text = t.Country;
PhoneNo.Text = t.PhoneNo;
EmailID.Text = t.Email;
Pincode.Text = t.Pin;
CheckIN.Text = t.CheckIn;
CheckOut.Text = t.CheckOut;
Adult.Text = t.AdultNo;
Child.Text = t.ChildNo;
Infant.Text = t.InfantNo;
RoomNo.Text = t.RoomNo;
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
string Stat = Statustxt.Text;
string FirstName = txtfName.Text;
string LastName = txtlName.Text;
string Address=txtAddr.Text;
string Cities=City.Text;
string States= State.Text;
string Countries =Country.Text;
string PhoneNos= PhoneNo.Text;;
string EmailId= EmailID.Text;
string PinCode=Pincode.Text;
string CIn=CheckIN.Text;
string COut=CheckOut.Text;
string AdultNo=Adult.Text;
string ChildNo=Child.Text;
string InfantNo=Infant.Text;
string RoomNos=RoomNo.Text;
TestObject obj = new TestObject();
obj.Stat=Statustxt.Text;
obj.FirstName = txtfName.Text;
obj.LastName = txtlName.Text;
obj.Address=txtAddr.Text;
obj.Cities=City.Text;
obj.States= State.Text;
obj.Countries =Country.Text;
obj.PhoneNos= PhoneNo.Text;;
obj.EmailId= EmailID.Text;
obj.PinCode=Pincode.Text;
obj.CIn=CheckIN.Text;
obj.COut=CheckOut.Text;
obj.AdultNo=Adult.Text;
obj.ChildNo=Child.Text;
obj.InfantNo=Infant.Text;
obj.RoomNos=RoomNo.Text;
string spName = "UPDATE";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(spName, conn);
conn.Open();
com.Parameters.AddWithValue("#Stat", obj.Stat);
com.Parameters.AddWithValue("#FirstName", obj.FirstName);
com.Parameters.AddWithValue("#LastName", obj.LastName);
com.Parameters.AddWithValue("#Address", obj.Address);
com.Parameters.AddWithValue("#Cities", obj.Cities);
com.Parameters.AddWithValue("#States", obj.States);
com.Parameters.AddWithValue("#Countries", obj.Countries);
com.Parameters.AddWithValue("#PhoneNos", obj.PhoneNos);
com.Parameters.AddWithValue("#EmailId", obj.EmailId);
com.Parameters.AddWithValue("#PinCode", obj.PinCode);
com.Parameters.AddWithValue("#CIn", obj.CIn);
com.Parameters.AddWithValue("#COut", obj.COut);
com.Parameters.AddWithValue("#AdultNo", obj.AdultNo);
com.Parameters.AddWithValue("#ChildNo", obj.ChildNo);
com.Parameters.AddWithValue("#InfantNo", obj.InfantNo);
com.Parameters.AddWithValue("#RoomNos", obj.RoomNos);
com.CommandType = CommandType.StoredProcedure;
com.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Customer Details updated in system");
}
}
SQL Server stored procedure:
ALTER PROCEDURE [dbo].[UPDATE]
#Id int,
#Stat nvarchar(100),
#FirstName nvarchar(100),
#LastName nvarchar(100),
#Address nvarchar(100),
#Cities nvarchar(100),
#States nvarchar(100),
#Countries nvarchar(100),
#PhoneNos int,
#EmailId nvarchar(100),
#PinCode int,
#CIn nvarchar(100),
#COut nvarchar(100),
#AdultNo int,
#ChildNo int,
#InfantNo int,
#RoomNos int
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
UPDATE [Hotel].[dbo].[Details] SET
[Status] = #Stat,
[FirstName] = #FirstName,
[LastName] = #LastName,
[Address] = #Address,
[City] = #Cities,
[State] =#States ,
[Country] = #Countries,
[PhoneNo] = #PhoneNos,
[EmailId] = #EmailId,
[Pincode] = #PinCode,
[CheckIn] = #CIn,
[CheckOut] = #COut,
[AdultNo] = #AdultNo,
[ChildNo] = #ChildNo,
[InfantNo] = #InfantNo,
[RoomNo] = #RoomNos
WHERE ID = #Id
END
a. as Mitch Wheat wrote in the comments, NEVER use keywords as procedures names.
b. as marc_s wrote in his comment - stop using .AddWithValue(). read the article he links to.
c. you never provide the #id parameter to the command , this is why you get the error.
d. this has nothing to do with winforms.
e. in the future, Please provide only the relevant code. if the problem is in the update button click, we don't need to see the entire form class, only the button click event handler.

Why is there a syntax error in my update statement in vb.net?

I have been working on my Update Sql statement, but cannot find the syntax error in my code. My insert statement is working, and I am selecting their login Id from another form to compare against.
conn.Open()
Dim SqlUpdate As String = "UPDATE tblLogin SET UserPassword =#UserPassword , FirstName =#FirstName , Surname =#Surname , DateofBirth =#DateofBirth , Phonenumber =#Phonenumber , Emailaddress = #Emailaddress , Administrator = #Administrator , Height = #Height , Weight = #Weight , WHERE UserID = #UserID "
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Parameters.AddWithValue("#UserPassword", passwordsubmitbox.Text)
.Parameters.AddWithValue("#FirstName", forenamebox.Text)
.Parameters.AddWithValue("#Surname", surnamebox.Text)
.Parameters.AddWithValue("#DateofBirth", DOBselection.Value)
.Parameters.AddWithValue("#Phonenumber", phonenumberbox.Text)
.Parameters.AddWithValue("#Emailaddress", emailadressbox.Text)
.Parameters.AddWithValue("#Administrator", "N")
.Parameters.AddWithValue("#Height", CInt(heightbox.Text))
.Parameters.AddWithValue("#Weight", CInt(weightbox.Text))
.Parameters.AddWithValue("#UserID", Formlogin.UsernameBox1.Text)
.Connection = conn
.ExecuteNonQuery()
End With
conn.Close()
Your query has syntax error remove , after #Weight
Weight = #Weight WHERE UserI ...

How to pass multiple command in one query?

Hi all how can I write code below more simply? ... so two sql(OleDb) command in one query.
con.open();
cmd.CommandText = "DELETE * FROM Customers WHERE ID_C = 1";
cmd.ExecuteNonQuery();
cmd.Clone();
cmd.CommandText = "DELETE * FROM Books WHERE ID_B = 1";
cmd.ExecuteNonQuery();
cmd.Clone();
con.close();
Provided that you don't need the number of rows affected (returned by ExecuteNonQuery) you can simply put both commands in the same SQL separated by ";"
con.open();
cmd.CommandText = "DELETE * FROM Customers WHERE ID_C = 1; DELETE * FROM Books WHERE ID_B = 1";
cmd.ExecuteNonQuery();
con.close();