Adding data to Access database using C# - 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();

Related

creating connection string for attached MDF file

what you see bellow is a part of my WPF project I used it to backup/restore my SQL server database and it works great but; when I want to make a setup file by advanced installer and I move MDF and LDF files created by SQL script to app directory to use in SQL express it doesn't work. Now I want to know what can I do with connection string so that backup/restore prosses can work correctly
private string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFileName=|DataDirectory|\\DBNBO.mdf;Database=DBNBO; Trusted_Connection=Yes;";
private void BtnBackup_OnClick(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
string query = "Backup Database [" + database + "] To Disk = '" + txtBackup.Text + "\\DB_backup.bak'";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
private void btnRestore_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
if (connection.State != ConnectionState.Open) connection.Open();
string query1 = string.Format("Alter Database [" + database + "] Set Single_User With Rollback Immediate");
SqlCommand command1 = new SqlCommand(query1, connection);
command1.ExecuteNonQuery();
string query2 = string.Format("Use Master Restore Database [" + database + "] From Disk = '" + txtRestore.Text + "' With Replace");
SqlCommand command2 = new SqlCommand(query2, connection);
command2.ExecuteNonQuery();
string query3 = string.Format("Alter Database [" + database + "] Set Multi_User");
SqlCommand command3 = new SqlCommand(query3, connection);
command3.ExecuteNonQuery();
connection.Close();
}

Invalid object name 'Main' error when inserting into Database - C# (WebForms), MySql

I know plenty of people have these issues, and I've actually tried to implement some of the suggestions to my code, however I'm getting errors that just don't make sense to me. This is my first time implementing database calls to my code. Can someone please tell me what I'm doing wrong? The following error pops up: ERROR: Invalid object name 'Main'. This is actually triggered by my exception so at least something is working. Otherwise, I don't know what the issue is. On the DB end, I have (username VARCHAR, email VARCHAR and number NCHAR) Please see the code below
static string path = Path.GetFullPath(Environment.CurrentDirectory);
static string databaseName = "u_DB.mdf";
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName + "; Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
// string query = "INSERT INTO UserInfo '" + textBox1.Text + "' and password = '" + textBox2.Text + "'";
string query = "insert into Main ([username], [email], [number]) values(#username,#email,#number)";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.AddWithValue("#number", SqlDbType.VarChar).Value = textBox1.Text;
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
MessageBox.Show("Added to Database");
else
MessageBox.Show("Nothing was added");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
con.Close();
}
}
Firstly, as Chetan assumed, do you have a main table?
The syntax of the query you are using is :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Furthermore,
AddWithValue(string parameterName, object value (<== The actual value to insert!));
in your case
AddWithValue("#number", textBox1.Text);
is enough.

C# store data error in Microsoft Access database

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?

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.

How to create exception for database file not found in c#

I have to connect my code to the access database but mainly, have to provide clear exception if that database file is not located in given location (like file not found). For this code :
string connStr =( #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";
conn1.Open();
cmd.ExecuteNonQuery();
I want to display message if test database is not present there. What can I do ? please suggest. thank you
I think you can use the static method File.Exists:
if(!File.Exists("Z:\\test.accdb"))
throw new FileNotFoundException();
try
{
string connStr =( #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO customer (id, name)" + " VALUES('3', 'C');";
conn1.Open();
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
//print the message you want;
}

Categories