I am trying to insert a new row into a SQL Server table from a Winforms application. As far as I know my query is correct but Visual Studio keeps returning an error:
Incorrect syntax near 'achternaam'
I hope that someone can point me in the right direction.
public void UpdateGegevens(int id, string voornaam, string achternaam, string functie, DateTime geboortedatum, decimal uurloon)
{
if (ReturnFirstTime(id) == true)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tbl_Gegevens (Id, voornaam, achternaam, geboortedatum, functie, uurloon) VALUES (#Id, #vn, #an, #gb, #f, #ul);";
command.Parameters.Add("#Id", SqlDbType.Int).Value = id;
command.Parameters.Add("#vn", SqlDbType.VarChar).Value = voornaam;
command.Parameters.Add("#an", SqlDbType.VarChar).Value = achternaam;
command.Parameters.Add("#f", SqlDbType.VarChar).Value = functie;
command.Parameters.Add("#gb", SqlDbType.Date).Value = geboortedatum;
command.Parameters.Add("#ul", SqlDbType.Money).Value = uurloon;
try
{
con.Open();
command.ExecuteScalar();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
else
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE tbl_Gegevens SET voornaam=#vn achternaam=#an geboortedatum=#gb funtie=#f uurloon=#ul WHERE Id = #Id;";
command.Parameters.AddWithValue("#Id", id);
command.Parameters.AddWithValue("#vn", voornaam);
command.Parameters.AddWithValue("#an", achternaam);
command.Parameters.AddWithValue("#gb", geboortedatum);
command.Parameters.AddWithValue("#f", functie);
command.Parameters.AddWithValue("#ul", uurloon);
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
Here is a specification of tbl_Gegevens:
create table [dbo].[tbl_Gegevens] (
[Id] int not null
, [voornaam] nvarchar(50) null
, [achternaam] nvarchar(50) null
, [geboortedatum] date null
, [functie] nvarchar(50) null
, [uurloon] smallmoney null
, primary key clustered ([Id] asc)
);
I think my dbms is ADO.Net.
This is the way i'm passing the info to the method:
private void btnConfirm_Click(object sender, EventArgs e)
{
if (tbName.Text != "" && tbSurname.Text != "" && tbFunction.Text
!= "" && dtpBirthdate.Value != date && nudSalary.Value != 0)
{
Database1.SetFirstTime(ID);
Database1.UpdateGegevens(ID, tbName.Text, tbSurname.Text, tbFunction.Text, dtpBirthdate.Value, nudSalary.Value);
this.Hide();
frmMain fm = new frmMain(ID);
fm.Show();
}
else
{
MessageBox.Show("Vul alle velden in!");
}
}
This is the query i use to get my id:
public int ReturnLoginID(string username, string password)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
int ID = 9999;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
ID = reader.GetInt32(0);
}
con.Close();
return ID;
}
In the UPDATE part of your code there are no commas to separate the fields in the SET list
command.CommandText = #"UPDATE tbl_Gegevens SET voornaam=#vn,
achternaam=#an, geboortedatum=#gb,
funtie=#f, uurloon=#ul WHERE Id = #Id;";
I think that this question could be used to underline the importance of using a debugger. This problem would be solved much sooner if you had stepped through your code using the debugger.
Related
I have a form which updates data. Query is executing but not updating the data. What's wrong? How to fix this?
It was working when I had concatenation but I changed it to parameters and now it's not working
private void button11_Click(object sender, EventArgs e)
{
try
{
if (SId.Text == "" || SellName.Text == "" || SellAge.Text == "" || SellPhone.Text == "" || SellPass.Text == "")
{
MessageBox.Show("Missing info");
}
string query = "UPDATE Sellers SET [SellerName] = #Name, [SellerAge] = #Age, [SellerPhone] = #Phone, [SellerPassword] = #Pass WHERE [SellerId] = #Id";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Id", SId.Text);
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Update successful!");
SId.Text = "";
SellName.Text = "";
SellPhone.Text = "";
SellPass.Text = "";
SellAge.Text = "";
Con.Close();
populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have to use a connection for the shortest time possible. Instead of conection.Open() use cmd.connection.Open(). I recommend to use this code:
var result=0;
using (var con= new SqlConnection(connectionString))
{
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Id", SId.Text); //??? if #Id is int or varchar?
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
cmd.Connection.Open();
result=cmd.ExecuteNonQuery();
}
if(result>0) MessageBox.Show("Update successful!");
else ....error
.... your code
I marked with ?? your #Id input parameter. I have some doubts that it is a string type. Check again. If it is int or any another type you will have to convert SId.Text to this type before to create a parameter.The same about #Age.
I want to retrieve the value of a certain column that contain an Oracle db generated sys_guid() within a transaction.
public string GetGUID(OracleConnection connection)
{
string guid = "";
connection.Open();
OracleCommand cmd = new OracleCommand();
OracleTransaction transaction;
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = transaction;
cmd.Connection = connection;
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO CUSTOMERS (NAME,DETAILS) VALUES (:nm, :dts)";
cmd.Parameters.Add("nm", OracleDbType.VarChar);
cmd.Parameters["nm"].Value = name;
cmd.Parameters.Add("dts", OracleDbType.VarChar);
cmd.Parameters["dts"].Value = details;
cmd.Prepare();
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
}
reader.Close();
transaction.Commit();
}
catch (Exception e)
{
transaction.Rollback();
Console.WriteLine(e.Message);
}
return guid;
}
Table CUSTOMERS have a column ORDER that creates a guid with SYS_GUID(), how can I retrieve that guid?
try returning .. into clause e.g.
...
using (OracleCommand cmd = connection.CreateCommand()) {
cmd.CommandText =
#"INSERT INTO CUSTOMERS (
NAME,
DETAILS)
VALUES (
:nm,
:dts)
RETURNING
""ORDER"" INTO :orderid";
cmd.Parameters.Add("nm", OracleDbType.VarChar);
cmd.Parameters["nm"].Value = name;
cmd.Parameters.Add("dts", OracleDbType.VarChar);
cmd.Parameters["dts"].Value = details;
cmd.Parameters.Add("orderid", OracleDbType.VarChar);
cmd.Parameters["orderid"].Direction = ParameterDirection.Output;
try {
cmd.ExecuteNonQuery(); // Just execute, nothing to read
transaction.Commit();
guid = Convert.ToString(cmd.Parameters["orderid"].Value);
}
catch (Exception e) { //TODO: put more specific exception type
transaction.Rollback();
Console.WriteLine(e.Message);
}
return guid;
}
...
I am attempting to create a simple news and image system, I first need to use SCOPE_IDENTITY() and execute scalar, but I'm not having much luck. I get a:
The name 'newID' does not exist in the current context
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("/images/admin/news/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
int newID = 0;
string strQuery = #"insert into tblFiles (FileName, FilePath) values(#FileName, #FilePath); select cast(scope_identity() As int);";
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#FileName", SqlDbType.VarChar).Value = FileName;
command.Parameters.Add("#FilePath", SqlDbType.VarChar).Value = "/images/admin/news/" + FileName;
try
{
connection.Open();
newID = (int)command.ExecuteScalar();
}
catch
{
}
}
}
if (newID > 0)
{
string strAddNewsQuery = #"insert into tblNews (newsTitle, newsDate, newsSummary, newsContent, newsPicID)
values(#newsTitle, #newsDate, #newsSummary, #newsContent, #newsPicID)";
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strAddNewsQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#newsTitle", SqlDbType.VarChar).Value = FileName;
command.Parameters.AddWithValue("#newsDate", txtnewsdate.Text);
command.Parameters.AddWithValue("#newsSummary", txtnewssummary.Text);
command.Parameters.AddWithValue("#newsContent", txtnewsmaincontent.Text);
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
finally {
connection.Close();
connection.Dispose();
}
}
}
}
}
An int does not have properties you can access. Change
command.Parameters.AddWithValue("#newsPicID", newID.Value);
into
command.Parameters.AddWithValue("#newsPicID", newID);
Even better is to use parameters with the database value type specified.
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
But you are trying to get the SCOPE_IDENTITY() of table tblNews, not from tblFiles to be used in tblNews as newsPicID. You need to get SCOPE_IDENTITY() from the first database command.
UPDATE
And you need to assign the connection to the command.
SqlCommand cmd = new SqlCommand(strQuery, con)
UPDATE 2
Here is a complete snippet to get you started. Notice the wrapping with using. This ensures proper disposal of connections.
int newID = 0;
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#FileName", SqlDbType.VarChar).Value = FileName;
command.Parameters.Add("#FilePath", SqlDbType.VarChar).Value = "/images/admin/news/" + FileName;
try
{
connection.Open();
newID = (int)command.ExecuteScalar();
}
catch
{
}
}
if (newID > 0)
{
using (SqlConnection connection = new SqlConnection(strConnString))
using (SqlCommand command = new SqlCommand(strAddNewsQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#newsTitle", SqlDbType.VarChar).Value = FileName;
//etc
command.Parameters.Add("#newsPicID", SqlDbType.Int).Value = newID;
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
}
}
I am trying to insert a row into the database. Below is my query:
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
string query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.AddWithValue("#x", insert[2]);
command.Parameters.AddWithValue("#y", insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
conn.Close();
}
}
When I run it nothing happens (Also no SQL errors). What am I doing wrong? I am sorry if this is a stupid question, I am merely a beginner.
This should work (I have tested this with a select query that does work).
Have you tried storing the query on a stored procedure and calling it from C#? ... Thats actually easier than making the query via hard code inside the C# code ... Just create a stored procedure that does whatever you want it to do, then call it from C# and add the parameters. It should look something like this:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Your_Conection_String_s_Name"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.Your_Stored_Procedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Input_Param_1", SqlDbType.VarChar, 18).Value = "C#_Parameter1";
cmd.Parameters.Add("#Input_Param_2", SqlDbType.VarChar, 45).Value = "C#Parameter_2";
cmd.Parameters.Add("#Input_Param_3", SqlDbType.VarChar, 45).Value = "C#Parameter_3";
cmd.Parameters.Add("#Input_Param_4", SqlDbType.Text).Value = "C#Parameter_4";
cmd.Parameters.Add("#Input_Param_5", SqlDbType.VarChar, 45).Value = "C#Parameter_5";
cmd.Parameters.Add("#Output_Parameter_1", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#Output_Parameter_2", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
"C#Output_Parameter_1" = "" + cmd.Parameters["#Output_Parameter_1"].Value;
"C#Output_Parameter_2" = "" + cmd.Parameters["#Output_Parameter_2"].Value;
Hope it helps.
My guess is that you have a type mismatch
If x, y are not int then substitute in the correct type
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
using (SqlCommand command = SqlCommand.CreateCommand())
{
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
command.Query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.Add("#x", SqlDbType.Int);
command.Parameters["#x"].Value = Int32.Parse(insert[2]);
command.Parameters.Add("#y", SqlDbType.Int);
command.Parameters["#y"].Value = Int32.Parse(insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
rowsRet = command.ExecuteNonQuery();
Console.WriteLine(rowsRet.ToString());
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
// op claims the insert is gone the next time the programs is run
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
}
}
Currently I am executing two queries against two different tables and getting this exception,
The connection was not closed. The connection's current state is open.
This is what I am trying to do,
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
connection.Open();
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
connection.Open();
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
I am doing this because Table2 has userID as foreign key and must be deleted before deleting user actually
you are calling Open() twice. You can remove the second call Open().
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
connection.Open();
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
// connection.Open(); // remove this line
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
The second connection.Open() is not required as it will be open from first statement.
Still to be on the safer side, you can use
if (connection.State == ConnectionState.Closed)
connection.Open();
The second connection.Open(); doesn't need to be there. The first one is enough; as the error message says, it's already open.
One connection can perform multiple queries, with only a single call to Open.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
I think this will work:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = deleteStatement;
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
cmd.CommandText = deleteStatement2;
int result = cmd.ExecuteNonQuery();
if (result == 1) BindData();
}
}