This update query isn't working when clicking the button. Here Group is the radio button but the program is throwing an excption
private void editAll_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DELL\source\repos\phoneBookwin\phoneBookwin\Database1.mdf;Integrated Security=True";
string value;
bool friendCheck = newFriends.Checked;
bool familyCheck = newFamily.Checked;
bool emergencyCheck = newEmergency.Checked;
bool collCheck = newColl.Checked;
if (friendCheck)
value = newFriends.Text;
else if (familyCheck)
value = newFamily.Text;
else if (emergencyCheck)
value = newEmergency.Text;
else if (collCheck)
value = newColl.Text;
else
value = "";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand Command = con.CreateCommand())
{
con.Open();
Command.CommandText = " update Contacts set Name =#newName, Contacts = #newNumber, Email = #newEmail, Group = #newGroup where Name = #changeName";
Command.Parameters.AddWithValue("#newName",newName.Text);
Command.Parameters.AddWithValue("#newNumber", newNumber.Text);
Command.Parameters.AddWithValue("#newEmail", newEmail.Text);
Command.Parameters.AddWithValue("#newGroup", value);
Command.Parameters.AddWithValue("#changeName", changeName.Text);
Command.ExecuteNonQuery();
con.Close();
}
this.Hide();
Form1 save = new Form1();
save.ShowDialog();
}
Exception thrown
'Incorrect syntax near the keyword 'Group'.'
Wrap keyword "Group" with square brackets in your SQL query:
update Contacts
set Name =#newName, Contacts = #newNumber, Email = #newEmail, [Group] = #newGroup
where Name = #changeName
As I already wrote in my comment here, first you should use square brackets for the keyword group
Command.CommandText = " update Contacts set [Group] = #newGroup, Name =#newName, Contacts = #newNumber, Email = #newEmail where Name = #changeName";
Second, avoid AddWithValue is has some problems as explained here
replace
Command.Parameters.Add(new AddWithValue("#newName",newName.Text);
with this
command.Parameters.Add(new SqlParameter("#newName", SqlDbType.VarChar)
{ Value = (newName.Text == "") ? (object)DBNull.Value : newName.Text });
Related
I am trying to update a databse entry under a specific id in my table when the users enter their ID number in a textBox.
At the moment it updates but updates all entries in my table except the entry containing the users ID number.
This is the code I am currently using:
private void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123");
SqlCommand check_User_Name = new SqlCommand("SELECT Id FROM NewVisitor WHERE (IDNumber = #IDNumber)", con);
check_User_Name.Parameters.AddWithValue("#IDNumber", idNumber_TxtBox.Text);
con.Open();
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
var connetionString = #"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123";
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer";
try
{
using (var connection = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#PersonVisit", SqlDbType.NVarChar).Value = personVisiting_TxtBox.Text;
command.Parameters.Add("#PurposeVisit", SqlDbType.NVarChar).Value = purposeOfVisit_CMBox.SelectedItem;
command.Parameters.Add("#Duration", SqlDbType.Date).Value = duration_dateTimePicker1.Value.Date;
command.Parameters.Add("#Disclaimer", SqlDbType.NVarChar).Value = disclaimer_CHKBox.Checked;
connection.Open();
command.ExecuteNonQuery();
}
}
}
The whole table has many more fields but would like to just update the above fields within that specific ID.
Thanks
You forgot the WHERE clause on the UPDATE statement, telling it specifically which records to update. It sounds like you just want to add the exact same WHERE clause that you have on your SELECT:
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer WHERE (IDNumber = #IDNumber)";
And don't forget to add the paramter for it:
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber_TxtBox.Text;
You may need to convert the input value to an integer first, I'm not 100% certain (it's been a while since I've had to use ADO.NET directly). Something like this:
if (!int.TryParse(idNumber_TxtBox.Text, out var idNumber))
{
// input wasn't an integer, handle the error
}
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber;
I Retrive values from admin table and then i store in String variable and finally i compare values my code is not redirect to another page
protected void Button1_Click(object sender, EventArgs e)
{
String uname = (String)txtuser.Text;
String upass = (String)txtp.Text;
String cuser = "";
String cpass = "";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HMSS"].ToString());
conn.Open();
String query = "select username,password from admin where username=#username";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("username", uname);
cmd.Parameters.AddWithValue("password", upass);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
cuser = rdr["username"].ToString();
cpass = rdr["password"].ToString();
}
if (cuser==uname && cpass==upass)
{
Session["user"] = cuser;
Response.Redirect("admin.aspx",true);
}
}
}
Can you check following code lines?
String uname = (String)txtuser.Text;
(string) implicit cast is not necessary: Text property is already a string.
conn.Open();
missing conn.Close(); it's better to add also try/catch
String query = "select username,password from admin where username=#username";
cmd.Parameters.AddWithValue("password", upass);
why don't you check also password in the query?
cuser = rdr["username"].ToString();
It means null value not allowed
if (cuser==uname && cpass==upass)
Problem with case sensitive/trim. In debug do you arrive on Response.Redirect?
Response.Redirect("admin.aspx",true);
Maybe ~/admin.aspx
try to change your condition to below
if (cuser.ToLower() == uname.ToLower() && cpass.ToLower() == upass.ToLower())
here is my code:
private void searchInDatabase()
{
MySqlConnection c = new MySqlConnection("datasource=localhost; username=root; password=123456; port=3306");
MySqlCommand mcd;
MySqlDataReader mdr;
String query;
try
{
c.Open();
query = "SELECT * FROM test.classmates WHERE first_name ='"+searchName.Text+"'";
mcd = new MySqlCommand(query, c);
mdr = mcd.ExecuteReader();
if(mdr.Read())
{
firstName.Text = mdr.GetString("first_name");
middleName.Text = mdr.GetString("middle_name");
lastName.Text = mdr.GetString("last_name");
age.Text = mdr.GetString("age");
}
else
{
MessageBox.Show("Result Not Found");
}
}
catch(Exception error)
{
MessageBox.Show("Error: "+error.Message);
}
finally
{
c.Close();
}
}
I would like to ask for a help if I have missed on anything or I am doing it wrong. If you have free time, I will much appreciate it if you will comment the perfect way to do I implement this problem: I want to get data from MySQL then put it in a textbox.
According to MSDN you need to pass the column number as parameter
public override string GetString(int i)
So try to pass the column number (starts from 0) of your column name. Assuming the first_name is the first column of your table then
firstName.Text = mdr.GetString(0);
UPDATE
Try to use MySqlConnectionStringBuilder
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "serverip/localhost";
conn_string.UserID = "my_user";
conn_string.Password = "password";
conn_string.Database = "my_db";
MySqlConnection conn = new MySqlConnection(conn_string.ToString();
First of all look at this sample of connection string and change your connection string:
'Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPasswor;'
If connection is OK send erorr message or full exception.
I have a form with a text box and button, such that when the user clicks the button, the specified name in the text box is added to a table in my sql database. The code for the button is as follows:
private void btnAddDiaryItem_Click(object sender, EventArgs e)
{
try
{
string strNewDiaryItem = txtAddDiaryItem.Text;
if (strNewDiaryItem.Length == 0)
{
MessageBox.Show("You have not specified the name of a new Diary Item");
return;
}
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES = ('" + strNewDiaryItem + "');";
cSqlQuery cS = new cSqlQuery(sqlText, "non query");
PopulateInitialDiaryItems();
MessageBox.Show("New Diary Item added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Unhandled Error: " + ex.Message);
}
}
The class cSqlQuery is a simple class that executes various T-SQL actions for me and its code is as follows:
class cSqlQuery
{
public string cSqlStat;
public DataTable cQueryResults;
public int cScalarResult;
public cSqlQuery()
{
this.cSqlStat = "empty";
}
public cSqlQuery(string paramSqlStat, string paramMode)
{
this.cSqlStat = paramSqlStat;
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
if (paramMode == "non query")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
sqlCom.ExecuteNonQuery();
linkToDB.Close();
}
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(cSqlStat, linkToDB))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
this.cScalarResult = (Int32)sqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public cSqlQuery(SqlCommand paramSqlCom, string paramMode)
{
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
paramSqlCom.Connection = linkToDB;
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(paramSqlCom))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
paramSqlCom.Connection = linkToDB;
this.cScalarResult = (Int32)paramSqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public string BuildConnectionString()
{
cConnectionString cCS = new cConnectionString();
return cCS.strConnect;
}
}
The class works well throughout my application so I don't think the error is in the class, but then I can't be sure.
When I click the button I get the following error message:
Incorrect syntax near =
Which is really annoying me, because when I run the exact same command in SQL Management Studio it works fine.
I'm sure I'm missing something rather simple, but after reading my code through many times, I'm struggling to see where I have gone wrong.
you have to remove = after values.
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES ('" + strNewDiaryItem + "');"
and try to use Parameterized queries to avoid Sql injection. use your code like this. Sql Parameters
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES (#DairyItem);"
YourCOmmandObj.Parameters.AddwithValue("#DairyItem",strNewDiaryIItem)
Remove the = after VALUES.
You do not need the =
A valid insert would look like
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Source: http://www.w3schools.com/sql/sql_insert.asp
Please use following:
insert into <table name> Values (value);
Remove "=", and also i would recommend you to use string.format() instead of string concatenation.
sqlText = string.format(INSERT INTO tblDiaryTypes (DiaryType) VALUES ('{0}'), strNewDiaryItem);"
i m trying to edit the values in database through textboxes in ASP.
first i retrived the values from database and set those values to the value property of textboxes on the form so that user can see the old values.
now, i want him to enter new values in the same textboxes and when he click on update the new values should be updated in the database.
can any one tell what i have to do to get those new values????
when to submit the form????
the code:
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label2.Text = ("Please ensure all fields are entered");
Label2.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [MachineGroups] SET ([MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded) WHERE ([MachineGroupID]= #node)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
You're not providing the #node parameter. so you should get an exception. Also change your sql statement like that without parenthesis :
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET [MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID";
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
EDIT : As you posted your insert page, your table should have an ID column to identify your record uniquely. As I see in your update SQL youe ID column's name is MachineGroupID. So to update your record, you should provide MachineGroupID as #node parameter. try to get this MachineGroupID value in your event and pass it into your Command.
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET
[MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,
[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID",cn; //add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
example :
SqlCommand cmdup = new SqlCommand("UPDATE [port1] SET [prt1]=#prt1 WHERE [no]= 1", cn);
cmdup.Parameters.Add("#prt1", TextBox1.Text);
cmdup.ExecuteNonQuery();
I think this may help your case, mention Connection at the last of your update command
ok i have the insert page which is working fine with this code.......
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour+DateTime.Now.Minute+DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label1.Text = ("Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("INSERT [MachineGroups] ([MachineGroupName],[MachineGroupDesc],[TimeAdded]) VALUES (#MachineGroupName,#MachineGroupDesc,#TimeAdded)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}