Unable to connect to .MDB database with ASP.NET C# - asp.net

I'm trying to create a simple user registration system using ASP.NET C# and an MS Access .mdb database. The problem is, whenever I attempt to register, the code fails at the OleDbCommand in the "try" and gets "caught" instead. I have used breakpoints in MS Visual Studio 2012 and all keys are present as far as I can tell. My code follows:
Here is my class where the registration method is located:
public static class DbUtil
{
private static OleDbConnection openConnection()
{
OleDbConnection con = new OleDbConnection();
try
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|MainDatabase.mdb";
con = new OleDbConnection(conString);
con.Open();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return con;
}
private static void closeConnection(OleDbConnection con)
{
try
{
con.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static bool registerUser(string email, string password)
{
try
{
using (OleDbConnection con = openConnection())
{
string sqlString = #"INSERT INTO Users (Email, Password) VALUES (?, ?)";
using (OleDbCommand command = new OleDbCommand(sqlString, con))
{
command.Parameters.AddWithValue("Email", email);
command.Parameters.AddWithValue("Password", password);
command.ExecuteNonQuery();
closeConnection(con);
return true;
}
}
}
catch
{
return false;
}
}
}
Here is where the method is called:
public void btnRegisterSubmit_Click(object sender, EventArgs e)
{
string strEmail = txtRegisterEmail.Text;
string strPassword = txtRegisterPassword.Text;
bool regSuccess = DbUtil.registerUser(strEmail, strPassword);
if (regSuccess == false)
{
Response.Redirect("Default.aspx?reg=fail");
}
else
{
if (regSuccess == true)
{
Response.Redirect("Default.aspx?reg=success");
}
else
{
Response.Redirect("Default.aspx?reg=error");
}
}
}
I'm currently using the praised parameter method, for the first time. I did use a simple concatenation method in the SQL string, but this yielded the same problem.
Also, there are no errors printed or exceptions thrown.
Any help at all would be highly appreciated. Thanks in advance!
UPDATE:
Exception:
System.Data.OleDb.OleDbException (0x80040E14): Syntax error in INSERT INTO statement. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at DbUtil.registerUser(String email, String password) in c:\Users\******\Documents\Visual Studio 2012\WebSites\********************\App_Code\DbUtil.cs:line 51

I'm not using any reserved words
password is indeed a reserved word in Access SQL. The following code fails with
OleDbException was unhandled: Syntax error in INSERT INTO statement.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace oledbTest1
{
class Program
{
static void Main(string[] args)
{
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\__tmp\testData.accdb;"))
{
conn.Open();
using (var cmd = new OleDbCommand(
#"INSERT INTO Users (Email, Password) VALUES (?, ?)",
conn))
{
cmd.Parameters.AddWithValue("?", "gord#example.com");
cmd.Parameters.AddWithValue("?", "myPassword");
cmd.ExecuteNonQuery();
}
conn.Close();
}
Console.WriteLine("Done.");
Console.ReadKey();
}
}
}
If I change the code to...
...
using (var cmd = new OleDbCommand(
#"INSERT INTO Users (Email, [Password]) VALUES (?, ?)",
conn))
{
...
...then it works fine.

Managed to get this fixed. I rewrote the registerUser() method, and removed the using blocks and it now works great. Here's the code with the removed parts commented:
public static bool registerUser(string email, string password)
{
try
{
//using (OleDbConnection con = openConnection())
//{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|MainDatabase.mdb");
string sqlString = "INSERT INTO [Users] ([Email], [Password]) VALUES (#Email, #Password)";
//using (OleDbCommand command = new OleDbCommand(sqlString, con))
//{
OleDbCommand command = new OleDbCommand(sqlString, con);
command.Parameters.AddWithValue("#Email", email);
command.Parameters.AddWithValue("#Password", password);
con.Open();
command.ExecuteNonQuery();
con.Close();
return true;
//}
//}
}
catch (Exception e)
{
return false;
//System.Diagnostics.Debug.WriteLine(e.Message);
}
}
Thanks for the comments :)

Related

ODBC connection to an .accdb file

I am trying to access a microsoft Access database file from a unity project i've been working on, but it keeps throwing an exception because it is unable to find the file and there has been no standard river has been selected.
The Code:
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Data;
using System.Data.Odbc;
public class AccDBReader : MonoBehaviour {
public string FileName;
public string Table_Name;
public string Column_name;
public DataTable Dt;
public string text;
public Text testtext;
public void Start()
{
FileName = "FestoMES.accdb";
Table_Name = "tblResource";
Column_name = "ResourceName";
ReadACCDB(Application.dataPath + "/" + FileName);
}
internal void ReadACCDB(string fileToReadFrom)
{
//string connection = "Driver = {FestoODBCTest}; Dbq = " + fileToReadFrom +"; Uid = ; Pwd = ;";
string connection = "Driver ={ Microsoft Access Driver(*.mdb, *.accdb)}; Dbq = " + fileToReadFrom + ";";
Debug.Log("The connection string");
Debug.Log(connection);
string sqlQuery = "SELECT "+Column_name+" FROM "+Table_Name;
OdbcConnection con = new OdbcConnection(connection);
OdbcCommand cmd = new OdbcCommand(sqlQuery, con);
try{
con.Open();
OdbcDataReader reader = cmd.ExecuteReader();
Dt.Load(reader);
reader.Close();
con.Close();
}
catch(Exception ex)
{
Debug.Log("Throws an exception");
Debug.Log(ex.ToString());
}
finally
{
if(con.State != ConnectionState.Closed)
{
con.Close();
}
con.Dispose();
}
if(Dt.Rows.Count > 0 && Dt.Columns.Count > 0)
{
Debug.Log(Dt.ToString());
testtext.text = Dt.ToString();
}
else
{
Debug.Log("Didnt find a table");
testtext.text = "Didnt Find a table";
}
}
}
This is the console log after the program has attempted to run:
The connection string
Driver ={ Microsoft Access Driver(*.mdb, *.accdb)}; Dbq = C:/Users/ASJ/Desktop/ODBC connections and Access/Assets/FestoMES.accdb;
System.Data.Odbc.OdbcException: Error [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified. at System.Data.Odbc.OdbcConnection.Open()[0x00000] in <filename unkown>:0
Didnt find a table
It doesnt seem to be able to find the file, yet the file exists at that position, does anyone have an idea of why the driver doesnt work in my case?
Figured out a way to solve it using a custom System DSN instead
internal void ReadACCDB()
{
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "FIL=MS ACCESS;DSN=FestoACCDBTest";
try
{
conn.Open();
OdbcCommand dbCommand = conn.CreateCommand();
dbCommand.CommandText = "SELECT ONo FROM tblFinOrder";
OdbcDataReader dbReader = dbCommand.ExecuteReader();
for (int i = 1; i < dbReader.FieldCount; i++)
{
testtext.text += " | " + dbReader.GetName(i);
}
}
catch(Exception ex)
{
testtext.text = ex.ToString();
}
finally
{
conn.Close();
}
}

creating sql connection object once and using it several times

i'm creating login and register page in MVC asp.net but problem is that for each purpose i have to do all SQl connection, command, try open etc which really makes it slow so i as wondering that if i can get rid of creating ti again and again and just create sqlconnection thing once and calling it again and again for login, registration etc
namespace LoginSys.Models
{
public class database
{
public ConnectionStatus connectDB(String name, String email, String pwd, String conStr)
{
// var con = conStr;
SqlConnection sqlCon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand();
sqlCom.Connection = sqlCon;
sqlCom.CommandText = "insert into tblRegister (userName, userEmail, userPwd) values (#name, #email, #pwd)";
sqlCom.Parameters.AddWithValue("#name", name);
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", pwd);
ConnectionStatus connectStatus = new ConnectionStatus();
int row_aff;
try
{
sqlCon.Open();
row_aff = sqlCom.ExecuteNonQuery();
connectStatus.Message = "OK";
}
catch(Exception ex)
{
connectStatus.Message = ex.Message;
}
finally
{
sqlCon.Close();
}
return connectStatus;
}
}
}
Actually you are not creating a new physical connection to the database. ADO.NET uses a connection pool. This means that even if you create a new instance of SqlConnection, you are not actually creating a new physical connection but are drawing one from the pool. Also when you call the .Close() method you are not actually closing the underlying connection. You are just returning it to the connection pool so that it can be reused.
So your code won't be slow because of that.
The only improvement I may recommend you to this code is to wrap the IDisposable objects in using statements:
public ConnectionStatus ConnectDB(string name, string email, string pwd, string conStr)
{
using (SqlConnection sqlCon = new SqlConnection(conStr))
using (SqlCommand sqlCom = sqlCon.CreateCommand())
{
sqlCon.Open();
sqlCom.CommandText = "insert into tblRegister (userName, userEmail, userPwd) values (#name, #email, #pwd)";
sqlCom.Parameters.AddWithValue("#name", name);
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", pwd);
ConnectionStatus connectStatus = new ConnectionStatus();
try
{
sqlCom.ExecuteNonQuery();
connectStatus.Message = "OK";
}
catch(Exception ex)
{
connectStatus.Message = ex.Message;
}
return connectStatus;
}
}

asp.net: upload images to SQL using imageupload

i have a database column 'images' which can hold binary data, for some reason the images doesnt want to upload. it doest pull any exceptions or aything wrong with the code:
here is extracts of the code
protected void BtnAdd_Click(object sender, EventArgs e)
{
string imgpath = FileUploadImage.FileName.ToString();
DBConnectivity.Add(imgpath);
}
here is the DBCoectivity Class:
public static void Add(string imgpath)
{
byte[] imgbt = null;
FileStream fstream = new FileStream(imgpath, FileMode.Open, FileAccess.Read);
BinaryReader BR = new BinaryReader(fstream);
imgbt = BR.ReadBytes((int)fstream.Length);
SqlConnection myConnection = GetConnection();
string myQuery = "INSERT INTO images( imagePath) VALUES ( #IMG )";
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.Parameters.Add(new SqlParameter("#IMG",imgbt));
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
This snippet works for me:
byte[] imgbt = null;
if (FileUploadImage.HasFile)
{
Stream photoStream = FileUploadImage.PostedFile.InputStream;
imgbt = new byte[FileUploadImage.PostedFile.ContentLength];
photoStream.Read(imgbt, 0, FileUploadImage.PostedFile.ContentLength);
}
Also, you were inserting the image name (misspelled as parameter to Add method and bad choice of variable name as it is not a path) into the database, not the binary data. It should read:
string myQuery = "INSERT INTO images(imgbt) VALUES (#IMG)";
Here's a sample tutorial which explains it better:
File Upload with ASP.NET

ASP.NET Mysql Data Reader not working

I try to autentificate to a database, to create a Login function. Every time I press the button I receive this error: System.InvalidOperationException: The connection is not open. at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Prepare() at start.CheckUserLogin(String username, String password) in c:\Users\RARES\Documents\Visual Studio 2010\WebSites\tem1\start.aspx.cs:line 46
Please tell me how can I read the data and check if the user and pass are the same as the ThextBox texts.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
if (CheckUserLogin(Label2.Text, Label3.Text))
{
Response.Redirect("login.aspx");
}
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
public Boolean CheckUserLogin(string username, string password)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
String query = "Select * from users where username= ?userName and password= ?passWord";
MySqlCommand cmd = new MySqlCommand(query,con);
cmd.Parameters.Add("?userName", TextBox1.Text);
cmd.Parameters.Add("?passWord", TextBox2.Text);
cmd.Prepare();
MySqlDataReader print = cmd.ExecuteReader();
bool read = print.Read();
if(username.Equals(print.GetString("1")) && password.Equals(print.GetString("2"))) return true;
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
return false;
}
You didn't open the connection before calling ExecuteReader method. Call con.Open. Your issue will be resolved.

Object reference not set to an instance of an object ERROR

I have few textboxes whose values are to be inserted into SQl table on Submit button click. But it gives me "Object reference not set to an instance of an object" Exception. Below is the code I have written for this. Please do help me in this.
contact_new.aspx.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime dtime;
dtime = DateTime.Now;
string ocode = offercode.Text;
string firstname = firstnamepreapp.Text;
string lastname = lastnamepreapp.Text;
string email = emailpreapp.Text;
string phoneno = phonepreapp.Text;
string timetocall = besttimepreapp.SelectedItem.Value;
string time = dtime.ToString();
//Insert the data into autoprequal table
<--- GIVES ME AN ERROR ON THIS LINE --->
Insert.insertINTOautoprequal(ocode, time, firstname, lastname, email, phoneno, timetocall);
}
Insert.cs (App_code class)
namespace InsertDataAccess
{
public class Insert
{
public Insert()
{
//
// TODO: Add constructor logic here
//
}
public static bool insertINTOautoprequal(string code, string time, string first, string last, string email, string phoneno, string timetocall)
{
bool success = false;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
conn.Open();
string query = "Insert INTO autoprequal(offercode, timeofday, firstname, lastname, emailID, phone, besttimetocall) Values(#offercode, #time, #first, #last, #email, #phoneno, #timetocall);";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
cmd.Parameters.AddWithValue("#offercode", code);
cmd.Parameters.AddWithValue("#time", time);
cmd.Parameters.AddWithValue("#first", first);
cmd.Parameters.AddWithValue("#last", last);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phoneno", phoneno);
cmd.Parameters.AddWithValue("#timetocall", timetocall);
if (cmd.ExecuteNonQuery() == 1) success = true;
else success = false;
return success;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
}
Step through the code, as the error is most likely bubbling up from the SQL insert routine. I woulud guess the connection string is not being pulled from the configuration file, but without stepping through that is a wild guess. I would take time to learn how to debug in Visual Studio, as it will help you easily spot what cannot be a problem so you can focus on what is likely to be the problem.

Resources