Unable to connect MS Access DB in Server - c#

I am trying to connect the MS Access Database from the server and finding no luck.
I see the below image("Insert Operation Error") message while trying to save the information.
Can anyone please help? What went wrong in the below code?
Insert Operation Error
protected void btnsave_Click(object sender, EventArgs e)
{
string constring = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath("DB\\Contact.DB");
string SqlString = "Insert Into BUREAUXDETUDES (mail1,mail2,tel1,tel2) Values (#mail1,#mail2,#tel1,#tel2)";
OleDbConnection con = new OleDbConnection(constring);
try
{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.Parameters.AddWithValue("#mail1", txtemail1.Text);
cmd.Parameters.AddWithValue("#mail2", txtemail2.Text);
cmd.Parameters.AddWithValue("#tel1", txttel1.Text);
cmd.Parameters.AddWithValue("#tel2", txttel2.Text);
cmd.ExecuteNonQuery();
lblmessage.Text = "Your Information Saved Successfully";
}
catch (Exception emsg)
{
lblmessage.Text = emsg.Message;
}
finally
{
con.Close();
}
}

The Error is telling you that the location of your .db file is incorrect.
You can change the path to the file in this line.
string constring = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath("DB\\Contact.DB");

You need to install Microsoft Excel engine first.
You can download it from the link bellow
https://www.microsoft.com/en-us/download/details.aspx?id=13255

Related

C# & SQL Server database error

I get an error on this line of code:
sda.Fill(dtbl);
Error message:
An attempt to attach an auto-named database for file C:\Users\...\Downloads\...\hax.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I have looked into this thread before and it did not solve my problem! Still broken.
I am a newbie to C# and this is my first SQL Server database. So I don't really know what to do. Here are some screenshots of the tables as well
https://gyazo.com/7558d5862d50a175b87861ac83cd34a4
https://gyazo.com/89c23bf3d499d2ff6f7fc361ff2aa283
Code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\...\Downloads\...\hax.mdf;Integrated Security=True;Connect Timeout=30");
string query = "Select * from Table Where username = '" + txtUsername.Text.Trim() + "' and password = '" + txtPassword.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
Form1 objFrmMain = new Form1();
this.Hide();
objFrmMain.Show();
}
else
{
MessageBox.Show("Check your username and password");
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
Login to SQL server management studio and remove a database attached with the same name. that way, it will be able to auto attach your database with that name.
NB: auto-attaching a database is considered a bad practice and will be removed from future SQL Server versions
use the following code
sda.Fill["dtbl"];

“error isam instalable cant be found”

I'm trying to connect my windows form app with my embedded database (.dbf) and I keep getting this message no matter what I do to the connection string:
error isam instalable cant be found
Here is the code I'm using to test the whole thing:
private void bGuardar_Click(object sender, EventArgs e)
{
try
{
string cadena = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =D:\\; Extended Properties = dBASE IV; UserID =; Password =;";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = cadena;
con.Open();
MessageBox.Show("conected");
con.Close();
}
catch (OleDbException exp)
{
MessageBox.Show("Error: " + exp.Message);
}
}
I think the problem is in the connection string.

file upload error, "not found on selected data source"

I've written the following code and when it was simply uploading the file to the folder everything was fine. I've changed it to insert the file name and file path into a database and I'm getting an error:
A field or property with the name 'DataUpload' was not found on the selected data source
DataUpload is the folder name and worked fine before. I'm probably missing something simple but I'm not seeing it.
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
try
{
FileUpload1.SaveAs(Server.MapPath("DataUpload\\" + FileUpload1.FileName));
Guid newGUID = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string InsertUser = "INSERT INTO UserUpload (ID, Comment, FilePath, FileName) VALUES (#ID, #Comment, #FilePath, #FileName)";
SqlCommand com = new SqlCommand(InsertUser, conn);
com.Parameters.AddWithValue("#ID", newGUID.ToString());
com.Parameters.AddWithValue("#Comment", TextBoxComment.Text);
com.Parameters.AddWithValue("#FilePath", "DataUpload/" + FileName);
com.Parameters.AddWithValue("#FileName", FileName);
com.ExecuteNonQuery();
LabelMessage.Text = ("Your Upload Is Complete");
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Add single quotes to the string you are creating for the FilePath, like:string.Format("'DataUpload/{0}'", FileName);

C# Inserting Data from a form into an access Database

I started learning about C# and have become stuck with inserting information from textboxes into an Access database when a click button is used.
The problem I get is during the adding process. The code executes the Try... Catch part and then returns an error saying "Microsoft Access Database Engine" and doesn't give any clues.
Here is the code:
namespace WindowsFormsApplication1
{
public partial class FormNewUser : Form
{
public FormNewUser()
{
InitializeComponent();
}
private void BTNSave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Copy Cegees\Cegees\Cegees\Login.accdb";
String Username = TEXTNewUser.Text;
String Password = TEXTNewPass.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Login (Username, Password) Values(#Username, #Password)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = Username;
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = Password;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}
Password is a reserved word. Bracket that field name to avoid confusing the db engine.
INSERT into Login (Username, [Password])
This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
and doesnt give any clues
Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
All you're examining is the source of the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.
Don't ignore the exception, it contains information about what went wrong and why.
There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at least capture the exception message, stack trace, and any inner exception(s). Currently you're ignoring the error, which is why you're not able to solve the error.
In your debugger, place a breakpoint inside the catch block and examine the details of the exception. You'll find it contains a lot of information.
private void Add_Click(object sender, EventArgs e) {
OleDbConnection con = new OleDbConnection(# "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}
My Code to insert data is not working. It showing no error but data is not showing in my database.
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Insertd!");
}
}

SQL Server Error, 'Keyword not supported 'datasource'

I'm currently trying to INSERT some values into a datasource, then display them on another page using the DataList control. However, after some testing and experimentation, I've found that the error comes from the very beginning.
Here is the code I have bound to my button.
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("DataSource=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName);
cmd.Parameters.AddWithValue("Phone", txtPhone);
cmd.Parameters.AddWithValue("Email", txtEmail);
cmd.Parameters.AddWithValue("Comments", txtComment);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
}
Here is the image of my webpage and the error it displays.
Please let me know if you need additional information.
Thanks in advance.
In your connection string, it should be "Data Source", not "DataSource". Just add a space.

Categories