ODBC connection to an .accdb file - odbc

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();
}
}

Related

Getting error "Database is locked" when I trye to save data i SQLITE DB

I have following class that connects to database but when I trye to call the method that saves data I get error "Database is locked". Could some one please help me to find the problem?
class Data
{
private SQLiteConnection con;
private void ConnectoDB()
{
String PathDB = Directory.GetCurrentDirectory();
PathDB += "\\SQLiteDB_MEDFit.db";
string cs = #"URI=file:" + PathDB;
string stm = "SELECT SQLITE_VERSION()";
con = new SQLiteConnection(cs);
con.Open();
var cmd = new SQLiteCommand(stm, con);
string version = cmd.ExecuteScalar().ToString();
}
public Boolean SaveToDatabase(string name, string number)
{
bool result = false;
try
{
ConnectoDB();
con.Execute("insert into People(name, number) values ('" + name+ "', '" + number+ "')");
con.Close();
result = true;
MessageBox.Show("Saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
}
The code that calls the "SaveToDatabase()"
string name = textBox1.Text();
string number = textBox2.Text();
Data connect = new Data();
connect.SavetoDB(name, number);

ASP.Net db connection issue

I'm new to ASP.Net & SQL Server and have the following code:
protected void btnShowData_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=DESKTOP-RV7DDL4;Initial Catalog=Demodb
;User ID=DESKTOP-RV7DDL4\dbname;Password=test123";
cnn = new SqlConnection(connectionString);
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = "";
sql = "Select TutorialID, TutorialName from demotb";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
lblName.Visible = false;
txtName.Visible = false;
lstLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdMale.Visible = false;
rdFemale.Visible = false;
btnSubmit.Visible = false;
}
When I run the project I receive the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.
I thought the connection was made so not sure why it says the db is closed?
Try to to explicitly open the connection via the Open method on the SQL connection class.
Perhaps a using statement is more appropriate here. Like so:
using (var cnn = new SqlConnection(connectionString))
{
// Use the connection
}
Thanks for your help. I re-jigged things around and added the .Open method and it works!
string connectionString = null;
SqlConnection cnn;
SqlCommand command;
string sql, Output = "";
connectionString = #"Data Source=DESKTOP-RV7DDL4\SQLEXPRESS;Initial Catalog=DemoDBase
;User ID=sa;Password=test1234";
cnn = new SqlConnection(connectionString);
sql = "Select TutorialID, TutorialName from demoTable";
cnn.Open();
command = new SqlCommand(sql, cnn);
SqlDataReader dataReader;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();

Importing and method call

I'm new to asp, and I cannot figure out how to the syntax for importing and adding a date object in the Default.aspx file.
The goal is to capture the get method and run the query. Here is what I've got:
<%
using System.Data.SqlClient;
string add = Request.QueryString["add"];
if (add != null && add.Length > 0)
{
Response.Output.Write("add = " + add);
string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
SqlConnection conn = null;
try
{
conn = new SqlConnection(connString);
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Conn = conn;
//cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO BuildVersion Values (#id, #dbVersion, #versionDate, #modifiedDate)";
cmd.Parameters.AddWithValue("#id", "2");
cmd.Parameters.AddWithValue("#dbVersion", "10.00.80404.00");
cmd.Parameters.AddWithValue("#versionDate", "4/4/2008 12:00:00 AM ");
cmd.Parameters.AddWithValue("#modifiedDate", "4/4/2008 12:00:00 AM ");
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Response.Output.Write(ex.ToString());
}
finally
{
if (conn != null)
{
conn.close();
}
}
}
%>
I need to learn how to do it inline as well as how to do it properly in a separate cs file. Thanks.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when I use scope identity

Here is ehat I try to do
on button_click I read the values from the text boxes and insert them in them in the database.
as tourist number for example maybe two or three tourists with ExecuteScalar; i get the ids of teh tourists which are inserted!
public void cmdInsert_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
string numtourist = (string)Session["tourist_number"];
for (int i = 0; i < Int32.Parse(numtourist); i++)
{
TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
TextBox tx888_1 = (TextBox)FindControl("txtMidNameK" + i.ToString());
TextBox tx888_2 = (TextBox)FindControl("txtLastNameK" + i.ToString());
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += " VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir", tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir", tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir", tx888_2.Text);
int added;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
lblproba.Text = "";
Tourist.Add(added);
lblproba.Text += Tourist.Count();
}
catch (Exception ex)
{
lblproba.Text += ex.Message;
}
finally
{
con.Close();
}
}
createReservation();
}
}
I call CreateReservationFunction AND i CREATE A NEW RESERVAION WITH THE ID OF THE USER WHO HAS MADE THE RESERVATION. wITH SELECT IDENTITY I TRY TO GET THE RESERVATION_ID of the reservation and here I get the exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack". So I wonder can this exception has something commn with the fact that in my solution exceptthe asp.net web projectI got library class in which I has .edmx file The entity framework model of my database and in my last form I don't use Ado,net but Entity framework
public void createReservation()
{
string insertSQL = "Insert INTO RESERVATIONS (User_ID) values (#User_ID) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#User_ID", 9);
try
{
con.Open();
string added = cmd.ExecuteScalar().ToString();
createTouristReservation(added);
}
catch (Exception ex)
{
lblproba.Text+= ex.Message;
}
}
Don't use ##IDENTITY but SCOPE_IDENTITY and add a semicolon between the insert and the select.
string insertSQL = #"INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)
VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir)
;SELECT CAST(scope_identity() AS int)";

Arithmetic operation resulted in an overflow

After updating my website on ii7 on window server 2008 from framework 3.5 to work with framework 4
i got my c# base database class stop working copmlitly with this error: "Arithmetic operation resulted in an overflow".
I am working with mysql server from different server.
I did not find any solution on this so i had very sadness to role bakce to framework 3.5
here is some of my logs for this error in the event viewr on my server:
Process information:
Process ID: 3680
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: OverflowException
Exception message: Arithmetic operation resulted in an overflow.
at DataAccess.ExecuteStringQuery(String strSQL) in d:\webSites\s2s\App_Code\DB\DataAccess.cs:line 214
at DataSelect.generalString(String rowName, String tableName, String idName, String ID) in d:\webSites\s2s\App_Code\DB\DataSelect.cs:line 48
at camsBaseShowWeb.OnPreInit(EventArgs e) in d:\webSites\s2s\App_Code\Bases\camsBaseShowWeb.cs:line 134
at System.Web.UI.Page.PerformPreInit()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
big thanks for any halp
i got this error - no matter wich function i try to call from this code
here is my code:
using System;
using System.Data;
//using Microsoft.Data.Odbc;
using System.Data.Odbc;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class DataAccess
{
#region Private Variables
private static DataAccess _DataAccess = null;
private static object _SyncLock = new object();
private string _strCon = "Driver={MySQL ODBC 5.1 Driver};Server=theIP;Database=theDatabase; UID=root;Password=thePassword;Option=3;";
private OdbcConnection myConnection = null;
#endregion
#region Instance Method
public static DataAccess Instance
{
get
{
lock (_SyncLock)
{
if (_DataAccess == null)
_DataAccess = new DataAccess();
return _DataAccess;
}
}
}
#endregion
#region Constractors
public DataAccess()
{
myConnection = new OdbcConnection(_strCon);
myConnection.Open();
}
#endregion
#region Public Functions
public OdbcDataReader ExecuteQueryReader(string strSQL)
{
try
{
OdbcCommand myCommand = new OdbcCommand(strSQL, myConnection);
return myCommand.ExecuteReader();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQueryReader SQL s2s", strSQL, ex);
}
throw ex;
}
}
public DataTable ExecuteQuery(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public DataView ExecuteQueryDV(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return new DataView(dt);
}
public DataTable ExecuteLimitedQuery(string strSQL, int startRow, int rowNum)
{
DataTable dt;
DataSet ds = new DataSet();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(ds, startRow, rowNum, "rowTable");
dt = (DataTable)ds.Tables["rowTable"];
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteLimitedQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public object ExecuteScalarQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteScalarQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj;
}
public string ExecuteStringQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (myConnection.State != ConnectionState.Open)
{
myConnection.Open();
if (myCommand != null) myCommand.Dispose();
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex2)
{
if (Dict.IsRemote == true)
{
sendMail("error - לאחר ניסיון שני ExecuteStringQuery SQL s2s", strSQL, ex2);
}
throw ex2;
}
}
else
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteStringQuery SQL s2s", strSQL, ex);
}
throw ex;
}
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj != null ? obj.ToString() : string.Empty;
}
public int ExecuteNoneQuery(string strSQL)
{
OdbcCommand myCommand = null;
int i;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
i = myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteNoneQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return i;
}
public int InsertGetLastID(string strSQL)
{
OdbcCommand myCommand = null;
int LastID = 0;
object objID = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
if (myCommand.ExecuteNonQuery() == 1)
{
myCommand = new OdbcCommand("SELECT LAST_INSERT_ID()", myConnection);
objID = myCommand.ExecuteScalar();
if (objID != null)
{
LastID = int.Parse(objID.ToString());
}
}
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error InsertGetLastID SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return LastID;
}
private void sendMail(string title, string sql, Exception ex)
{
string body = string.Empty +
"SQL:\n\n" + sql + "\n\n" +
"Exeption:\n\n" + ex.Message + "\n\n" +
"Stack Trace:\n\n" + ex.StackTrace + "\n\n" +
"Source:\n\n" + ex.Source + "\n\n";
mailSend mailS = new mailSend("theMail", "mailTo", title, body);
}
#endregion
}
I was getting this too since the upgrade to .Net 4.0
System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Data.Odbc.OdbcDataReader.GetSqlType(Int32 i)
at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i)
at System.Data.Odbc.OdbcCommand.ExecuteScalar()
at Server.Engines.MyRunUO.DatabaseCommandQueue.Thread_Start() in d:\RunUO\Sec
ondAge\Scripts\Engines\MyRunUO\DatabaseCommandQueue.cs:line 117
OdbcConnection version is System.Data.dll, v4.0.30319
Using "{MySQL ODBC 5.1 Driver}" (actually 5.01.06.00) against MySQL 5.1.40-community via TCP/IP on localhost.
The query was any variation of:
SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='chardb'
The (apparently) offending lines:
command.CommandText = string.Format("SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='{0}'", m_timeStampName); // Line 116
object result = command.ExecuteScalar(); // Line 117
This occurred with an x64 compile only, i.e. using the x64 mySQL driver.
This was fixed by upgrading from mySQL ODBC driver 5.01.06.00 to 5.01.08.00
conver to boolean function does not work when
1. Development is done on 32 bit OS
2. Implementation is done on 64 bit OS
When I altered the code for Convert.ToBoolean function, It worked normally.

Resources