MSAccess database update not updating using c# - c#

I am making a database system. I've implemented the INSERT function properly but when I tried implementing the UPDATE function, I couldn't make any changes to the database. I don;t know where I went wrong.
Note: username is declared as string
Here is the function handling the UPDATE:
private void btnUpdate_Click(object sender, EventArgs e)
{
string q = "UPDATE [registrationinfo] SET [Password]='?', [EmailAdd]='?', [HomeAdd]='?' WHERE [Username]='?'";
OleDbConnection connect = new OleDbConnection(MyConnectionString);
connect.Open();
try
{
OleDbCommand command = new OleDbCommand(q,connect);
command.Parameters.AddWithValue("#Password", txt_password.Text);
command.Parameters.AddWithValue("#EmailAdd", txt_eadd.Text);
command.Parameters.AddWithValue("#HomeAdd", txt_homeadd.Text);
command.Parameters.AddWithValue("Username", username);
command.ExecuteNonQuery();
txt_password.Clear();
txt_eadd.Clear();
txt_homeadd.Clear();
txt_conPass.Clear();
}
catch (Exception ex)
{
connect.Close();
MessageBox.Show(ex.Message.ToString());
}
connect.Close();
}

When using a parameterized query you do not need to put single quotes (') around text parameters in your CommandText, so you should be using something like this:
string q = "UPDATE [registrationinfo] SET [Password]=?, [EmailAdd]=?, [HomeAdd]=? WHERE [Username]=?";

Related

Connection String Not Working- Not Allowing Connection to Database made in VS (C# Visual Studio)

I am currently working on building an attendance tracker that will take the user's input data and add it to a database table. I'm running into an issue where my connection string will not connect to the database? I've copied it directly as is, and even tried a few different tutorials with alternative ways with no success. This is for an assignment however, our SQL portion was quite small and I'm not sure where to go from here. Please let me know if something in my code needs revisited.
When I run the code I get the "unable to connect" exception I created below. I need it to run and add the user input to the table.
I have also noticed that my database connection often disconnects unless I refresh, is this common?
namespace AttendanceTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void signInButton_Click(object sender, EventArgs e)
{
string connectionString = null;
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\soupy\Desktop\AttendanceTracker\AttendanceTrackerDatabase.mdf; Integrated Security = SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#Student_Name", nameTextBox.Text);
cmd.Parameters.AddWithValue("#Student_ID", studentIDTextBox.Text);
cmd.Parameters.AddWithValue("#Class", classDropDown.Text);
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Your sign in has been recorded successfully!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unable to open attendance tracker for updating.");
}
}
When using Parameter objects, you should ensure that the variable names are consistent.
Please modify your code as follows
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#studentName", nameTextBox.Text); // Modified to "studentName"
cmd.Parameters.AddWithValue("#studentID", studentIDTextBox.Text); // Modified to "studentID"
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
cmd.Parameters.AddWithValue("#class", classDropDown.Text); // Modified to "class"

Adding records to MS Access database through C#

I am attempting to add items to an Access database in C#. I have code that seems to work (I can open and close a database), but the button click event produces errors. I have been searching on Google for the whole afternoon but no joy. My code is:
private void button26_Click(object sender, EventArgs e)
{ //Setup tab LoadDatabase
try
{
connection.Open();
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO Main('Prop', 'Value', 'Default','Type') VALUES('one', 'Kelly', 'Jill','one')";
cmd.ExecuteNonQuery();
button26.Text = "Done Insert";
connection.Close();
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
connection.Close();
}
}
And the error I get is:
Error System.InvalidOperationException: ExecuteNonQuery: Connection property has not been initialized.
at System.Data.OleDb.OleDbCommand.ValidateConnection(String method)
at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method)
? at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at CrewCheifSettingsBeta3.Form1.button26_Click(Object sender, EventArgs e) in C:\Somepath\Form1.cs:line 49
Clearly something wrong with the connection string, and that it's not SQL-injection proof either.
The problem is well known. A command need to know the connection to use to execute the command text. However you have other problems in your code.
Connection objects (like commands) should not be global, but created when they are needed and destroyed after. The using statement is very usefull here because you don't have to explicitly close and destroy these objects and you will never have resource leaks when an exception occurs.
Second, when you use field names that are also reserved keywords in your database you should enclose these name in some kind of escape characters. These characters for Access are the open/close brackets not the single quote.
private void button26_Click(object sender, EventArgs e)
{
try
{
string cmdText = #"INSERT INTO Main
([Prop], [Value], [Default],[Type])
VALUES('one', 'Kelly', 'Jill','one')";
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
connection.Open();
cmd.ExecuteNonQuery();
button26.Text = "Done Insert";
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
}
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
}
}
Finally I don't know if your fields are of text type. You pass literal texts so they should be of text type and remember to use parameters when you switch this simple code to your actual values.
Assign Connection property as below line.
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
Per #Steve's comment, there is no connection associated with the command when you just instantiate it like that. You need to either set the Connection property of the command or better yet use connection.CreateCommand() to create the command in the first place in which case it will already be associated with the connection (cleaner).

How to properly store data into database

I'm facing a very simple problem, but I don't know how to solve it. I have a simple textBox, and local database, Database1.mdf, with one table: emp. Inserting data works fine, but when I restart application, then these data are lost.
I'm also using a dataSet, where I can see data in the table - the record is properly inserted, but it is lost when I restart the app. What am I missing?
I'm running a C# application (VS2013):
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::base.Properties.Settings.Default.Database1ConnectionString);
try {
string sql = "INSERT INTO emp (name) VALUES ('" + textBox1.Text + "')";
SqlCommand exesql = new SqlCommand(sql, cn);
cn.Open();
exesql.ExecuteNonQuery();
MessageBox.Show("Hooray!!");
this.empTableAdapter.Fill(this.database1DataSet.emp);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}
Set Database1.mdf's "Copy to Output Directory" property value to "Do not copy" from Properties box.

Bringing up pictures from a database as I search for the name

I need help with this program I'm trying to write. I'm a complete noob at this, so forgive my shortcomings but I'm trying to create a search feature, in which it completes the names from a database as soon as you write the first letter. I've done this succesfully, now I have to bring up pictures also from the same database, I'm getting some errors. Could you take a look at my code and tell me what's wrong? And also is this enough?
note: My aim is to bring up pictures AS they write the name.
void showpic(string queryStr)
{
SqlConnection conn = new SqlConnection(#"server adress");
conn.Open();
SqlCommand execute = new SqlCommand("SELECT Pernr from View_PhoneBook where DisplayName=" + textBox1.Text, conn);
try
{
StringCollection View_Phonebook = new StringCollection();
SqlDataReader reader = execute.ExecuteReader();
while (reader.Read())
{
View_Phonebook.Add(reader.GetString(0));
}
pictureBox1.ImageLocation.Equals("url" + View_Phonebook + ".jpg");
}
catch (Exception ex)
{
}
conn.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
showpic(textBox1.Text);
}
Add quotes to the string in this line, like so:
SqlCommand execute = new SqlCommand('SELECT Pernr from View_PhoneBook where DisplayName= #text', conn);
execute.Parameters.Add("text", SqlDbType.Text).Value = Textbox1.text;
I will suggest, you should do this using a StoredProc.
Its not a solution to the prob, but another way to do this.
That way you will not face any such probs.
Moreover, havign a StoredProc is better then constructing a query on every text change event.

SQL server express, cannot read or write in C#

I have a code written that automatically adds and reads information from my SQL Server 2012 Express table, Logins. But it wont work, here is the code:
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=myComputer;" + "server=MYCOMPUTER-PC\\SQLEXPRESS;" +
"Trusted_Connection=yes;" + "database=loginTest; " + "connection timeout=5");
try
{
myConnection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO dbo.Logins Values ('John','Password','Admin')", myConnection);
try
{
SqlDataReader myReader = null;
SqlCommand myCommand1 = new SqlCommand("select * from Logins",
myConnection);
myReader = myCommand1.ExecuteReader();
while (myReader.Read())
{
MessageBox.Show(myReader["Column1"].ToString());
MessageBox.Show(myReader["Column2"].ToString());
}
}
catch (Exception ex1)
{
MessageBox.Show(ex1.ToString());
}
}
I have debugged the program and it all seems to go through fine, it skips over :
{
MessageBox.Show(myReader["Column1"].ToString());
MessageBox.Show(myReader["Column2"].ToString());
}
for some reason, and it doesnt write the values i told it to.
Can anyone tell me why? Im a beginner at SQL, so go easy please :)
PS It doesnt fire out any error codes or exceptions
You Logins table doesn't have any records, if you mean you want to try inserting some record first to test, it's this line causing your problem:
SqlCommand myCommand = new SqlCommand("INSERT INTO dbo.Logins Values ('John','Password','Admin')", myConnection);
myCommand.ExecuteNonQuery();//Do this to insert something into your Logins first.
it skips over [...]
Presumably that's because there's no data to read, so myReader.Read() just returns false.
it doesnt write the values i told it to.
You don't actually tell it to write anything. You create a SqlCommand to insert data, but you never execute it. You need to use myCommand.ExecuteNonQuery. You should also use using statements for the commands, the connection and the reader, to make sure they get closed properly.

Categories

Resources