C# store data error in Microsoft Access database - c#

private void okbtn_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Desktop\GameMuseumManagementSystem.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Email = txtEmail.Text.ToString();
String Password = txtPassword.Text.ToString();
String my_query = "INSERT INTO Member(Member_Name,Member_Password,Member_Email)VALUES('" + Name + "','" + Email + "','" + Password + "')";
OleDbCommand cmd = new OleDbCommand(my_query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
I am coding for the member registeration for a guest to use it. I have 3 pieces of data, member_name, member_ID, and password. I coded this and I get an error. My Visual Studio is connected to my MS Access database via the tools, after I write this code, the data can't be stored in Access, what should I do now? Any suggestion?

Related

An object or column name is missing or empty (0x80131904)

I'm getting this error when I try to use the button to restore the database:
"An object or column name is missing or empty".
The thing is that I'm using offline database file (.mdf) and when I click ok on this error and press the restore button again, it works like a charm.
There's the code:
private void RestoreButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
if (con.State!=ConnectionState.Open)
{
con.Open();
}
try
{
string sqlStmt2 = string.Format("ALTER DATABASE [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE [" + database + "] FROM DISK='" + textBox2.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [" + database + "] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("Database succesfully restored!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
There's the full error.

Webform controls are not validated

I have a couple of textboxes and some dropdownlists on a register page. When the user presses submit, I want the values to be validated and if they are correct I want to enter them in the database. My values are not being validated, even if I call validation manually and check whether they are valid or not. So my code is putting empty stuff in the DB...
protected void btn_registreren_Click(object sender, EventArgs e)
{
Validate();
if (Page.IsValid)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\Database11.accdb";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Gebruikers(gebruikersnaam, geboortedatum, admin, wachtwoord) VALUES (#gebruikersnaam, #geboortedatum, #admin, #wachtwoord)";
cmd.Parameters.AddWithValue("#gebruikersnaam", txt_email.Text);
cmd.Parameters.AddWithValue("#geboortedatum", txt_dag.Text + "-" + ddl_maand.SelectedValue + "-" + txt_jaar.Text);
cmd.Parameters.AddWithValue("#admin", false);
cmd.Parameters.AddWithValue("#wachtwoord", txt_wachtwoord.Text);
try
{
conn.Open();
lblConnState.Text = "Connection is: " + conn.State.ToString();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblConnState.Text = exc.Message;
}
finally
{
conn.Close();
lblConnState2.Text = "<br />Connection is: " + conn.State.ToString();
}
}
else
{
lblConnState2.Text = "not valid";
}
}
I tried: giving all fields, validators and submit button the same validation group. I tried doing this in the page load as well. Also looked around extensively on the internet but couldn't find what is wrong.

Adding data to Access database using C#

I'm playing around with C# and Access databases trying to connect them and insert data through a web to the Access database, however I keep getting this:
"A first chance exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll"
on my output console and get nothing else.
not sure what I'm doing wrong but any help will do. Thanks
here's my code for getting the connection:
public partial class reg_Test : System.Web.UI.Page
{
private static OleDbConnection GetConnection()
{
String connString;
connString = #"Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\Wisal\Documents\Visual Studio 2012\WebSites\WebSite3\test-db1.mdb";
return new OleDbConnection(connString);
}
here's my code for the submit button after user fill the text boxes Name and Surname:
protected void submitButtn_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = GetConnection();
String TextBox1 = nameBox.Text;
String TextBox2 = snameBox.Text;
try
{
myConnection.Open();
Console.WriteLine("Connection Opened");
String myQuery = "INSERT INTO client values ([name], surname) values ('" + nameBox.Text + "','" + snameBox.Text + "');";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
}
}
Change your query statement like below.
myConnection.Open();
Console.WriteLine("Connection Opened");
String myQuery = "INSERT INTO client([name], surname) values ('" + nameBox.Text "','"+ snameBox.Text + "');";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();

Data from c# application into Ms Access transferring incorrectly

...
using System.Data;
using System.Data.OleDb;
namespace accessloginapp
{
public partial class Ramen : Form
{
private OleDbConnection connection = new OleDbConnection();
public Ramen()
{
InitializeComponent();
connection.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\...\Users.accdb;Persist Security Info=False;";
}
private void btn_Save_Click(object sender, EventArgs e)
{
try{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText =
"insert into userdata (Username,[Password]) values('" +
txt_Username + "','" + txt_Password + "')";
command.ExecuteNonQuery();
MessageBox.Show("Users added and saved");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
I'm sorry if I do not understand much, I'm fairly to new to this. When I save data such as username and password in my application, the data is inserted as what I input but with added text, Example: I would send the username "Mark" to be inserted, but when I go to look at my database, it is put in as "System.Windows.Forms.TextBox, Text: Mark". How can I change this to only inserting the Username I Input?
You need to use Text property of textbox control, to fetch the actual text stored:-
command.CommandText = "insert into userdata (Username,[Password])
values('" + txt_Username.Text + "','" + txt_Password.Text + "')";
Apart from this please note your query is open for SQL Injection attack.
So, you should use Parameterized query something like this:-
command.CommandText = "insert into userdata (Username,[Password])
values(?,?)";
command.Parameters.Add("?",OleDbType.VarChar,20).Value = txt_Username.Text;
and similarly add parameter for #Password.

Why I get syntax error in this update statement?

I wanted to update a table in my m/s access database where my the user entered a new password in order to replace the old one but i have syntax error in the update statement. Please help!
public partial class resetPassword : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
string userName = (string) Session["username"];
string str = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\JetStar\database\JetstarDb.accdb";
var con = new OleDbConnection(str);
con.Open();
string pwd = Request.Form["conPassword"];
OleDbCommand cmd = new OleDbCommand("UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'", con);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Your password has been changed successfully.");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
}
Probably this happends because password is a reserved keyword on Microsoft Access. You should use it with square brackets as [password]
But more important
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Don't store your passwords as a plain text. Read: Best way to store password in database
Use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection con = new OleDbConnection(str))
using(OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE [users] SET [password] = ? WHERE username = ?";
cmd.Parameters.Add("pass", OleDbType.VarChar).Value = pwd;
cmd.Parameters.Add("user", OleDbType.VarChar).Value = userName;
con.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Your password has been changed successfully.");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
92.3% (a) of all DB problems become obvious if you just print the command before you use it, and read the error message.
So replace:
OleDbCommand cmd = new OleDbCommand("UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'", con);
with something like:
String s = "UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'";
Console.WriteLine(s);
OleDbCommand cmd = new OleDbCommand(s, con);
Then post the results of:
Response.Write(ex.Message);
for all to see, and examine what it tells you very carefully.
(a) A statistic I just plucked out of nowhere - actual value may be wildly different.

Categories