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;
}
Related
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();
As a group we are working on a project and need to save the data collected in the label in a field in an access database. However we have been having some troubles with this function.
Here is the code what i have tried so far:
We changed the values from lbl.View.text to "1" for testing purposes, but still no luck.
private void complete_btn_Click(object sender, EventArgs e)
{
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\meSch\log.accdb;Persist Security Info=True";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = connStr;
OleDbCommand cmd = con.CreateCommand();
// error is in insert statement somehwhere.
cmd.CommandText = "INSERT INTO Users (TimeStamp, Interest, TotalTime)" + "VALUES('" + "1" +"', '"+ "1" + "','" + "1" + "');";
// conn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\meSch\log.accdb;Persist Security Info=True");
// cmd = new OleDbCommand("", con);
// cmd.Parameters.AddWithValue("#TimeStamp", lblView.Text);
// cmd.Parameters.AddWithValue("#Interest", lblView.Text);
// cmd.Parameters.AddWithValue("#TotalTime", lblView.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Based on your exception message, TimeStamp is a reserved keyword in MS Access. You need to use it with square brackets like [TimeStamp]. As a better way, change it to non-reserved word which is meaningful for your column.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"INSERT INTO Users (TimeStamp, Interest, TotalTime)
VALUES(?, ?, ?)";
cmd.Parameter.AddwithValue("#p1", "1");
cmd.Parameter.AddwithValue("#p2", "1");
cmd.Parameter.AddwithValue("#p3", "1");
con.Open();
cmd.ExecuteNonQuery();
}
Trying update record dont know why i am getting error
Exception Details: System.Data.OleDb.OleDbException: No value given for one or more required parameters.
this is my code please guide me.
public static string lasttable;
public static string newtable;
newtable = "c" + cont.ToString();
lasttable = input;
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb; Persist Security Info=False;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string query = "UPDATE [LastInfo] SET [LastAlbum]=#newtable WHERE [LastAlbum]=#lasttable";
OleDbCommand comd = new OleDbCommand();
comd.Parameters.Add("#LastAlbum", OleDbType.VarChar);
comd.Parameters["#LastAlbum"].Value = newtable;
comd.CommandText = query;
comd.Connection = conn;
comd.ExecuteNonQuery();
conn.Close();
You are using OleDb and OleDb doesn't care about parameter names.
However you need to add a parameter for every placeholder present in the command text and in the same order in which they appear.
You have two parameter (#newtable and #lasttable) but you add just one parameter (and you name it wrongly, but, as I have said, that doesn't matter for OleDb).
You need to add the second parameter #lasttable
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb; Persist Security Info=False;";
using(OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
string query = "UPDATE [LastInfo] SET [LastAlbum]=#newtable WHERE [LastAlbum]=#lasttable";
OleDbCommand comd = new OleDbCommand();
comd.Parameters.Add("#newTable", OleDbType.VarChar);
comd.Parameters["#newTable"].Value = newtable;
comd.Parameters.Add("#lastTable", OleDbType.VarChar);
comd.Parameters["#lastTable"].Value = lasttable;
comd.CommandText = query;
comd.Connection = conn;
comd.ExecuteNonQuery();
}
I need to add a text box value to SQL Server database table. Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(str);
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
con.Close();
}
But, data should not add in table... please help me...
thanks for ur help...
Try debugging your query first if it works i think your connection with your db isnt working.
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
is there supposed to be this '.' after data source Data Source=.\\SQLEXPRESS
try this and tell me what is the message information content
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;";
using( SqlConnection con = new SqlConnection(str)){
try{
con.Open();
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
}
catch{
MessageBox.Show("connection is failed!!");
}
}
}
try this
SqlConnection con = new SqlConnection(#"Data Source=SL-20\SQLEXPRESS;Initial Catalog=TestDB;User ID=sa;Password=sl123;");
string query = " insert into name(name)values('" + TextboxTest.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
I am working on WPF application in C#. Database is SQL Server 2008. I have a table "Employee" in database, I need to insert a row in it. I have successfully connected with database, but when I tried to execute this line:
cmd = new SqlCommand(cmdText, conn);
This errors comes up: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(String, System.Data.SqlClient.SqlConnection)' has some invalid arguments.
Here is my code:
private void addbtn_Click(object sender, RoutedEventArgs e)
{
//FUNCTION TO ADD NEW EMPLOYEE RECORD IN DATABASE
try
{
conn.ConnectionString = "Data Source=AZEEMPC;" + "Initial Catalog=IEPL_Attendance_DB;";
conn.Open();
cmdText = "INSERT INTO Employee VALUES ('" + strCurrentString + "','" + emp_name.Text + "')";
cmd = new SqlCommand(cmdText, conn);
data_ad = new SqlDataAdapter(cmd);
data = new DataSet();
data_ad.Fill(data);
MessageBox.Show("Record Inserted Successfully!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any suggestions?
conn needs to be of type SqlConnection - can you confirm that it is?
SqlConnection conn;
Because it's a native SQL Server connection, you don't need to pass the driver name in the connection string.
conn.ConnectionString = "Server=AZEEMPC;Database=IEPL_Attendance_DB;Trusted_Connection=true;";