This is my CustomerRegister class, but I cant seem to input data from my addressTextBox into the CustomerTbl.
DataBase dbObj = new DataBase();
string selStr = "Update CustomerTbl Set customer_address = '" + addressTextBox.Text + "' Where custID = " + "NULL";
int i = dbObj.ExecuteNonQuery(selStr);
This is my DataBase class but return comdObj.ExecuteNonQuery(); doesnt work as there is not such custID named NULL. So how do i program in such a way so that i am able to constantly update the database when a new user registers?
class DataBase
{
string connStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\OOPG\Banking Mini Project Raynard\Banking Mini Project Raynard\Database1.mdf;Integrated Security = True";
SqlConnection connObj;
SqlCommand comdObj;
SqlDataReader dR;
public DataBase()
{
connObj = new SqlConnection(connStr);
connObj.Open();
}
public SqlDataReader ExecuteReader(string selStr)
{
comdObj = new SqlCommand(selStr, connObj);
dR = comdObj.ExecuteReader();
return dR;
}
public int ExecuteNonQuery(string sqlStr)
{
comdObj = new SqlCommand(sqlStr, connObj);
return comdObj.ExecuteNonQuery();
}
}
First you should create a connection to SQL database before executing any query. After then you should be able to insert data before updating any data into database. After you insert data successfully you can update data using above command text. Here is some sample code for inserting data for registering customer.
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection; // <== lacking
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into CustomerTbl (CustId, Name, Address) VALUES (#CustId, #Name, #Address)";
command.Parameters.AddWithValue("#CustId", name);
command.Parameters.AddWithValue("#Name", userId);
command.Parameters.AddWithValue("#Address", idDepart);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close();
}
}
If you're adding a record, you're going to need to INSERT, not UPDATE. For example (here using "Dapper" to do all the heavy work, including parameter handling):
using Dapper;
//...
void UpsertAddress(int? id, string address)
{
if (id is null)
{
connection.Execute("insert CustomerTbl (customer_address) values (#address);",
new { address }); // possibly using the OUTPUT clause to fetch an IDENTITY
}
else
{
connection.Execute(
"update CustomerTbl set customer_address = #address where custID = #id;",
new { id, address });
}
}
Related
I can't figure out how to save individual data from an Access database into variables.
I understand that you can save variables like this:
int memberID;
cmd.CommandText = "SELECT * FROM MemberDetails WHERE [MemberID] =#MemberID";
cmd.Parameters.AddWithValue("#MemberID", memberID);
try
{
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
lblName.Text = (memberID);
}
con.Close();
}
catch (Exception)
{
throw;
}
However I want to save all the data into separate variables, something like this:
cmd.CommandText = "SELECT [MemberID] = #MemberID, [Name] = #Name, [Surname] = #Surname";
cmd.Parameters.AddWithValue("#MemberID", memberID);
cmd.Parameters.AddWithValue("#Name", name);
cmd.Parameters.AddWithValue("#Surname", surname);
This obviously doesn't work (otherwise I wouldn't be here) but is anything like this possible and how would I go about doing this?
Maybe have a look at this great tutorial from Microsoft, it explains on how to query an MS Access database with C# and how to process the results: https://msdn.microsoft.com/en-us/library/ms971485.aspx
What you could do to achieve the desired result is something like this (this is a slightly modified example from the article mentioned above):
OleDbConnection conn = null;
OleDbDataReader reader = null;
try
{
conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + Server.MapPath("MyDataFolder/MyAccessDb.mdb"));
conn.Open();
OleDbCommand cmd =
new OleDbCommand("Select MemberID, Name, Surname FROM MemberDetails WHERE MemberID = #MemberID", conn);
cmd.Parameters.AddWithValue("#MemberID", memberID);
reader = cmd.ExecuteReader();
while(reader.Read())
{
memberID = reader.GetInt32(reader.GetOrdinal("MemberID"));
name = reader["Name"].ToString();
surname = reader["Surname"].ToString();
}
}
finally
{
if (reader != null) reader.Close();
if (conn != null) conn.Close();
}
Be carefull though, this will only work correctly when there is only one result returned in be the database query. When multiple records are returned only the last will be stored in the variables.
When you need to capture multiple results you will probably want to create a Member class, create an instance for each record and add the instance to a members list. Something like this:
public class Member
{
public int MemberId {get; set;}
public string Name {get; set;}
public string Surname {get; set;}
}
public IList<Member> GetMembers()
{
OleDbConnection conn = null;
OleDbDataReader reader = null;
try
{
conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + Server.MapPath("MyDataFolder/MyAccessDb.mdb"));
conn.Open();
OleDbCommand cmd =
new OleDbCommand("Select MemberID, Name, Surname FROM MemberDetails", conn);
reader = cmd.ExecuteReader();
var members = new List<Member>();
while(reader.Read())
{
var member = new Member();
member.MemberID = reader.GetInt32(reader.GetOrdinal("MemberID"));
member.Name = reader["Name"].ToString();
member.Surname = reader["Surname"].ToString();
members.Add(member);
}
return members;
}
finally
{
if (reader != null) reader.Close();
if (conn != null) conn.Close();
}
return null;
}
Correct me if I'm wrong, but it looks as though you're attempting to retrieve a row where you have a known MemberID. If that's the case, then you can always do something like this
int memberID = [some number];
DataTable results = new DataTable(); //Your SQL row will be "saved" in here
string command = string.Format("select * from MemberDetails where MemberID = {0}", memberID);
using (SqlDataAdapter sda = new SqlDataAdapter(command, con))
{
sda.Fill(results); //Your DataTable now has your values
}
All you need is something where you can feed the memberID to your condition variable.
Bussiness Access Layer :
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
id = cmd.ExecuteNonQuery();
cmd = null;
con.Close();
return id;
}
Login.cs
protected void Button1_Click(object sender, EventArgs e)
{
int id = BusinessAccessLayer.login(userlogin.Text.Trim(), pwdlogin.Text.Trim());
if (id > 0)
{
message.Text = " valid";
}
else
{
message.Text = "in valid";
}
}
Okay, there are multiple things wrong here:
1) You should use using statements to make sure you close your connection and command even if exceptions are thrown
2) You should use parameterized SQL instead of putting the values directly into your SQL statement, to avoid SQL Injection Attacks
3) You appear to be storing passwords in plain text. Don't do that. Use a salted hash or something similar (ideally something slow to compute).
4) You're ignoring .NET naming conventions; methods should be in PascalCase
5) Your SQL never looks at any field which appears to be related to the user ID. It's not clear what you expect ExecuteNonQuery to return, but if you want the actual ID, you'll need to refer to it in the SQL. (Even if initially you just want to know whether or not the user's password is valid, I strongly suspect that at some point you'll want to user the real user ID, so you should make your code return it. If you really only want to know whether or not the password is valid, you should change the method's return type to bool.)
6) You're using ExecuteNonQuery when your command clearly is a query. Either use ExecuteReader or ExecuteScalar instead. (ExecuteNonQuery is meant for insert, delete and update statements, and it returns you the number of rows affected by the command.)
So something like:
public static int Login(string user, string password)
{
using (var conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
string sql = "select Id, PasswordHash from logins where Username=#Username";
using (var command = new SqlCommand(sql))
{
command.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
using (var reader = command.ExecuteRead())
{
if (reader.Read())
{
int id = reader.GetInt32(0);
string hash = reader.GetString(1);
// TODO: Hash provided password with the same salt and compare
// results
if (CheckPassword(password, hash))
{
return id;
}
}
return 0; // Or use an int? return type and return null
}
}
}
}
The ExecuteNonQuery is used for For UPDATE, INSERT, and DELETE statements.
For SELECT statements, use ExecuteReader
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id++;
}
cmd = null;
reader.Close();
con.Close();
return id;
}
You can't use .ExecuteNonQuery if you want a result. Use .ExecuteReader.
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserId FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
id = reader.GetInt32("UserId");
reader.Close();
con.Close();
return id;
}
I've been trawling through pages and pages on the internet for days now trying different approaches and I'm still not sure how I should be doing this.
On my third InsertCommand, I'd like to reference a column on the other 2 tables.
// Populate a DataSet from multiple Tables... Works fine
sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("SELECT * FROM hardware", sqlConn);
sqlDA.Fill(ds, "Hardware");
sqlDA.SelectCommand.CommandText = "SELECT * FROM software";
sqlDA.Fill(ds, "Software");
sqlDA.SelectCommand.CommandText = "SELECT * FROM join_hardware_software";
sqlDA.Fill(ds, "HS Join");
// After DataSet has been changed, perform an Insert on relevant tables...
updatedDs = ds.GetChanges();
SqlCommand DAInsertCommand = new SqlCommand();
DAInsertCommand.CommandText = "INSERT INTO hardware (host, model, serial) VALUES (#host, #model, #serial)";
DAInsertCommand.Parameters.AddWithValue("#host", null).SourceColumn = "host";
DAInsertCommand.Parameters.AddWithValue("#model", null).SourceColumn = "model";
DAInsertCommand.Parameters.AddWithValue("#serial", null).SourceColumn = "serial";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Hardware"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO software (description) VALUES (#software)";
DAInsertCommand.Parameters.AddWithValue("#software", null).SourceColumn = "description";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Software"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO join_hardware_software (hardware_id, software_id) VALUES (#hardware_id, #software_id)";
// *****
DAInsertCommand.Parameters.AddWithValue("#hardware_id", null).SourceColumn = "?"; // I want to set this to be set to my 'hardware' table to the 'id' column.
DAInsertCommand.Parameters.AddWithValue("#software_id", null).SourceColumn = "?"; // I want to set this to be set to my 'software' table to the 'id' column.
// *****
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "HS Join");
Could somebody please tell me where I am going wrong and how I could potentially overcome this? Many thanks! :)
With regards to your comments this seems to be one of those occasions where if you and I were sat next to each other we'd get this sorted but it's a bit tricky.
This is code I've used when working with SqlConnection and SqlCommand. There might be stuff here that would help you.
public static void RunSqlCommandText(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
}
public static int RunSqlAndReturnId(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
int id = -1;
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
var returnvalue = comm.ExecuteScalar();
if (returnvalue != null) {
id = (int)returnvalue;
}
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
return id;
}
Okay referring to my first question code in the main, I want the user to enter employee name at runtime and then i take this name which user has entered and compare it with the e_name of my emp table , if it exists i want to display all information of that employee , how can I achieve this ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ConnectCsharppToMySQL
{
public class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
string name;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "test";
uid = "root";
password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO emp (e_name, age) VALUES('Pooja R', '21')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
string query = "UPDATE emp SET e_name='Peachy', age='22' WHERE e_name='Pooja R'";
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM emp where e_name=(/*I WANT USER ENTERED NAME TO GET INSERTED HERE*/)";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["e_id"] + "");
list[1].Add(dataReader["e_name"] + "");
list[2].Add(dataReader["age"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
public static void Main(String[] args)
{
DBConnect db1 = new DBConnect();
Console.WriteLine("Initializing");
db1.Initialize();
Console.WriteLine("Search :");
Console.WriteLine("Enter the employee name");
db1.name = Console.ReadLine();
db1.Select();
Console.ReadLine();
}
}
}
This method will need to accept a parameter:
public List<string>[] Select()
Something like this, most likely:
public List<string>[] Select(string name)
Then, within that method, you can reference the name variable. When calling that method, you would supply that variable:
var listOfResults = dbConnectInstance.Select(someNameValue);
Once that variable is in your method, you can use it in your SQL query. You would do this by setting it as a parameter in your SELECT query. Something like this, perhaps (keep in mind this is free-hand code, I don't have the MySql .NET library handy to test):
string query = "SELECT * FROM emp where e_name=#ename";
//... (opening the connection like you do now, etc.)
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.Add("#ename", MySqlDbType.VarChar, 80).Value = name;
//... (continuing as you do now)
What this essentially does is create a placeholder in the query called #ename (it can be called anything, the # is the important part for being a placeholder) which expects to be replaced with an actual value. Adding an item to the Parameters collection on the command object is what replaces the placeholder with the value.
This is called "parameterized queries" in ADO.NET (which is the database connection technology you're using). It helps keep your queries dynamic (one query can be re-used with different values) as well as helps prevent SQL injection attacks (note that I said helps prevent, as it's not a magic bullet and increased understanding of the subject in general is your best defense).
More information specifically about the MySql .NET library's queries and parameters can be found starting here.
use MySqlParameter as :
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand ("SELECT * FROM emp where e_name =#Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.AddWithValue("#Name", name);// name is get from console read line.
//
// Read in the SELECT results.
//
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// read each value
}
}
}
EDIT
here are the changes you need to do
//add name as Select method parameter
public List<string>[] Select(string name)
{
string query = "SELECT * FROM emp where e_name =#Name"; // change your select query
....
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("#Name", name) // add this line after creating command
....
}
call above method as
db1.name = Console.ReadLine();
db1.Select(db1.name);
Iam fairly new to SQLClient and all, and iam having a problem with my SQL tables..when ever i run my code, the data, rather than getting updated, attaches itself to the already existing records in the tables..here's my code
SqlConnection conneciones = new SqlConnection(connectionString);
SqlCommand cmd;
conneciones.Open();
//put values into SQL DATABASE Table 1
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
cmd = new SqlCommand("insert into URL_Entries values('" + CleanedURLlist[ok] + "' , '" + DateTime.Now + "' , '" + leak + "' )", conneciones);
cmd.ExecuteNonQuery();
}
conneciones.Dispose();
Take a look at these functions, i hope you understand better on update , insert and delete functions..
Code snippets for reading, inserting, updating and deleting a records using asp.net and c# and sql server database
static void Read()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeDetails", conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("Id = ", reader["Id"]);
Console.WriteLine("Name = ", reader["Name"]);
Console.WriteLine("Address = ", reader["Address"]);
}
}
reader.Close();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Update()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE EmployeeDetails SET Name=#NewName, Address=#NewAddress WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Munna Hussain");
cmd.Parameters.AddWithValue("#Address", "Kerala");
int rows = cmd.ExecuteNonQuery();
//rows number of record got updated
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Delete()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("DELETE FROM EmployeeDetails " +
"WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
int rows = cmd.ExecuteNonQuery();
//rows number of record got deleted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
Your code should be inserting new records, but I'm not clear on whether it is not doing that, or you mean to update existing records.
Aside from that, understanding that you are new to working with SQL Server, there are a couple of things you should be aware of.
You should use using to automatically dispose resources. This will also close your connection for you so you don't have open connections hanging around.
You should use parameters to protect against sql injection attacks. Another benefit of using parameters in your case is that you don't need to create new commands for every statement.
For example:
using (var connection = new SqlConnection(connectionString)
using (var command = connection.CreateCommand())
{
command.CommandText = "insert into URL_Entries values(#url, #now, #leak)";
command.Parameters.AddWithValue("#now", DateTime.Now);
command.Parameters.AddWithValue("#lead", leak);
// update to correspond to your definition of the table column
var urlParameter = command.Parameters.Add(new SqlParameter("#url", SqlDbType.VarChar, 100));
connection.Open();
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
urlParameter.Value = CleanedURLlist[ok];
command.ExecuteNonQuery();
}
}
Per your comment, if you want to do an update, you'll need to include the parameter(s) that identify the rows to update. If this is a single row, use the primary key value:
command.CommandText = "update URL_Entries set UrlColumn = #url, ModifiedDate = #now where ID = #id";
You're using an INSERT function, that is 'ADD NEW RECORDS'
If you want an update, you'll want an UPDATE function
UPDATE tablename
SET column1 = 'x', column2 = 'y'
WHERE id = z