I'm new to C# and connecting to databases.
The problem is: whenever I try to connect to DB by running this code:
string connparams = "server=127.0.0.1;uid=root;pwd=12345;database=test;";
try
{
MySqlConnection connection = new MySqlConnection(connparams);
}
catch (System.ArgumentException me)
{
Console.WriteLine(me.ToString());
}
connection.Open();
connection.Close();
I get the window "The application is in break mode"
When I take a look at the events window I can see an exception with description "No source code". When I try to see the implementations of functions in MySQLConnection I can see none of them, only declarations. So what should I do/redo/reinstall in order to solve this? Using VS2017, .NET Framework 4.6.1, Connector/NET (MySQL)
Related
I have a c# winform project that supposes to save data to SQLite database, I've already used the dll properly and it runs without error, but I get an exception when trigger the method with buttonClick event
here the exception i got : Keyword not supported :'version'.
this the connection string:
"Data Source = Diary.db;Version = 3;New = False;Compress = True;";
and this the complete method :
private void AddToDbaseSQL3()
{
try{
string query = "insert into Diary(title,date,mood,wheater,content)
values('"+TitleTextbox.Text+"','"
+dateTimePicker.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','"
+MoodCombobox.SelectedItem+"','"
+WheaterCombobox.SelectedItem+"','"
+ContentTextbox.Text+"');";;
SqlConnection connect2 = new SqlConnection(connection2);
SqlCommand cmd = new SqlCommand(query,connect2);
SqlDataReader read;
connect2.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
}
MessageBox.Show("created");
TitleTextbox.Text = "Title";
TitleTextbox.ForeColor = SystemColors.ControlLight;
ContentTextbox.Clear();
connect2.Close();
}catch(Exception e){
MessageBox.Show(e.Message);
}
}
I've looked to this link:
Keyword not supported: 'version'
and it said to change SqlConnection to SQLiteConnection but it ended with an error, can you tell what's is the right connection string ? or there is something wrong from my code/method? please tell me, thank you, I'm sorry because it's my first time using the SQLite
SqlConnection from System.Data.SqlClient is for SQL Server.
You need an dedicated SQLite ADO.NET provider.
You can found the System.Data.SQLite provider from SQLite team here:
https://system.data.sqlite.org
Or you can use any libre or commercial provider.
You can also use the free and open-source SQLite ODBC driver that works fine and allow to use VS Visual Designers to create strongly typed ADO.NET DataSets, in addition to the use of OdbcConnection, OdbcCommand and so on:
http://www.ch-werner.de/sqliteodbc
C# Reading data from existing SQLite database
I have an asp.net C# application (.net 4.0) connected to SQL Server 2012 using ADO.Net and am encountering an error which says:
[InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
I very well know what a DataReader is but, my problem is getting this error in below conditions:
I have not at all used any DataReader in my application, I have only
used DataAdapters everywhere. The code works fine while running in
local environment and there is no errors.
Application works fine even after deployment in IIS7 when used by a
single user.
The error only occurs when multiple users starts using the website hosted in IIS7.
Kindly help, I am also doubting for any problems with my hosting in IIS7
After a lot of trial and error, finally I found out that it's a problem with SqlConnections. What I used to do was open a connection at the instantiation of my DAL layer object. So, whenever two methods from the same DAL object called together, it used to throw the error.
I solved it by opening and closing a connection in every call to the database. Now it all works fine. This also allows max number of users to use the application at a time. Below is my code sample from DAL:-
DataTable dt = new DataTable();
try
{
using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
{
if (sqlcon.State == ConnectionState.Closed)
sqlcon.Open();
SqlCommand sqlCommand = new SqlCommand
{
Connection = sqlcon,
CommandType = CommandType.StoredProcedure,
CommandText = "MyStoredProc"
};
sqlCommand.Parameters.AddWithValue("#Parameter1", Parameter1);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand))
{
adapter.Fill(dt);
}
}
return dt;
}
catch (Exception exp)
{
LogHelper.LogError(string.Concat("Exception Details: ", ExceptionFormatter.WriteExceptionDetail(exp)));
throw exp;
}
finally
{
dt.Dispose();
}
Please post a better way of doing it if you know any, thank you.
I am using this code but getting an error of 'Object reference not set to an instance of an object.' at con.open() ? what am I doing wrong ?
I have already download and installed ODAC component version 10 , 11 ,12 trying each one at the failure of the latest one but still same error
using Oracle.DataAccess.Client;
namespace WindowsFormsApplication1
{
class OraTest
{
public OracleConnection con = new OracleConnection();
public void Connect()
{
con.ConnectionString = "Data Source=(DESCRIPTION= (ADDRESS = (PROTOCOL = TCP)(HOST =myip) (PORT = myport))(CONNECT_DATA = (SERVER = dedicated)(SERVICE_NAME = mydb)));User ID=myid;Password=mypass;";
con.Open(); //error here
}
public void Close()
{
con.Close();
con.Dispose();
}
}
Please go through this link
Getting Started with Oracle Data Provider for .NET (C# Version)
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/GettingStartedNETVersion/GettingStartedNETVersion.htm
If you add a try/catch block in Connect(), you'll be able to catch the error.
For example:
When opening an oracle connection, connection object is null
I added the try catch block, and it returned ORA12154 - TNS could not
be resolved. After some research, I added an SID to my tnsnames.ora
file in my ODP for .NET Oracle home path, and it worked
See also Troubleshooting Oracle Net Services for troubleshooting possible connection issues from Oracle clients (such as your C# program).
But your first step is absolutely to determine the Oracle-level error (for example, ORA-12543 (could not connect to server host) or TNS-12514 (could not find service name)
MSDN: OracleException Class
public void ShowOracleException()
{
OracleConnection myConnection =
new OracleConnection("Data Source=Oracle8i;Integrated Security=yes");
try
{
myConnection.Open();
}
catch (OracleException e)
{
string errorMessage = "Code: " + e.Code + "\n" +
"Message: " + e.Message;
System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
log.Source = "My Application";
log.WriteEntry(errorMessage);
Console.WriteLine("An exception occurred. Please contact your system administrator.");
}
}
It's significant that con.ConnectionString = xyz works, but the following `con.Open()" fails. This means .Net is creating the C# object, but Oracle/TNS is failing when you try to use it.
ADDITIONAL SUGGESTIONS:
Re-read
When opening an oracle connection, connection object is null.
Read all of the suggestions, including the one about "Data Source in your connection string".
Focus on your connection string. It couldn't hurt to specify the connection string in your OracleConnection() constructor, if possible. Here's another link:
ODP.NET Connection exception
It would be great if you can verify connectivity from your PC with some other Oracle client, besides your C#/.Net program. To verify you're talking to the right TNS host and service, with the correct username/password. For example, maybe you have SQLDeveloper or sqlplus.
Finally, re-read the TNS troubleshooting link:
https://docs.oracle.com/cd/E11882_01/network.112/e41945/trouble.htm#NETAG016
What worked for me with the same error was to simply switch from the 'plain' Oracle DataAccess library, to the 'Managed' version.
This is an extemely easy change to make -
Add a Reference in your c# project to the Oracle.ManagedDataAccess library
Replace the existing use statements at the top of your Oracle client code with the following:
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
Include the Oracle.ManagedDataAccess.dll file with your exe
I have a service running, that is connected to a few clients. It has been up and running for weeks and this function is called many times every minute, I have a few catches in the different function, but this exception made it all the way to crash. I never seen the issue before. Whan can make this occure?
Stack:
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
at System.Data.OleDb.OleDbServicesWrapper.GetDataSource(System.Data.OleDb.OleDbConnectionString, System.Data.OleDb.DataSourceWrapper ByRef)
at System.Data.OleDb.OleDbConnectionInternal..ctor(System.Data.OleDb.OleDbConnectionString, System.Data.OleDb.OleDbConnection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(System.Data.Common.DbConnectionOptions, System.Object, System.Data.ProviderBase.DbConnectionPool, System.Data.Common.DbConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionPoolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(System.Data.Common.DbConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at EServer.Database.DBManager.DoesObjectExsist(System.String)
at EServer.Database.DBManager.setObjectOnline(System.String, Boolean, System.String, System.String)
at EServer.Network.SocketListener.handleToDo()
at EServer.Network.Token.ProcessData(System.Net.Sockets.SocketAsyncEventArgs)
at EServer.Network.SocketListener.ProcessReceive(System.Net.Sockets.SocketAsyncEventArgs)
at EServer.Network.SocketListener.OnIOCompleted(System.Object, System.Net.Sockets.SocketAsyncEventArgs)
at System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(System.Net.Sockets.SocketAsyncEventArgs)
at System.Net.Sockets.SocketAsyncEventArgs.ExecutionCallback(System.Object)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(System.Net.Sockets.SocketError, Int32, System.Net.Sockets.SocketFlags)
at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
Code:
public bool DoesObjectExsist(String ID)
{
try
{
String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + dbPath + "'";
string mySelectQuery = "SELECT * FROM Object WHERE ID = \"" + ID + "\"";
OleDbConnection myConnection = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
myConnection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
return true;
}
}
finally
{
myReader.Close();
myConnection.Close();
}
return false;
}
catch (Exception e)
{
return false;
}
}
EF Core Update
The followings sections are a bit dated and are about EF6 and .NET Framework 4.x.
Nowadays, if you are using .NET (Core), use the EntityFrameworkCore.Jet EF Core provider. Use the latest prerelease, that references the 5.0.0 OLE DB libraries, that contain some major bugfixes.
AccessViolationException
This issue is a bug within the ACE 2010 engine. A workaround can be found in the original bug report on microsoft connect (see FranzT):
In my Applicationn I have the same problem. MS Access DB is a backend for this app(C#, .NET 2.0, VS 2005).
When in connection string as provider OLEDB.4.0 is used, it works fine. When the data access provider is ACE.OLEDB.12 I get an Exception if OpenFileDialog is used.
In connection string is possibel to set many parameters, OLE DB Services too.
When OLE DB Services=default (-13, pooling disabled) I get the
Exception. When OLE DB Services=EnableAll (-1, pooling enabled) it
works fine.
If I set OLE DB Services=-2 (EnableAll without pooling) I get the Exception.
My workaround is: set the OLE DB services=-1(EnableAll).
The workaround is based on the research of a microsoft forum user by the name of Elmar Boye, who goes into detail about the nature of the issue (though in German):
https://social.msdn.microsoft.com/Forums/de-DE/500055e5-6189-418c-b119-fdc0367e0969/accessviolationexception-bei-openfiledialog-nach-ffnen-und-schlieen-einer-2-form?forum=dotnetframeworkde
Basically, the ACE 2010 engine is accessing memory it doesn't own. And if the database is already unloaded at the time the engine accesses the memory, the exception is thrown. To workaround the issue, connection pooling can be used, since it keeps the database connection open and therefore the database in memory. It can be enabled using different combinations of OLE DB Services flags.
A good flag value is the original default, which enables all services (though this default seems to be overwritten by a registry key, which is why it makes sense to manually provide the value in the connection string):
OLE DB Services=-1
Though the bug report addresses a problem within the open file dialog, the root cause is the same as for other AccessViolationException cases using the ACE 2010 provider for Access.
There is also a link to a Hotfix that supposedly fixes the issue.
By the way, this exception does not occur using the Microsoft.Jet.OLEDB.4.0 provider.
JetEntityFrameworkProvider
For those like me who are using the JetEntityFrameworkProvider by bubibubi make sure that you are using the workaround in your production connection string, but not in your connection string you use for applying database migrations, because it will throw a OleDbException E_UNEXPECTED(0x8000FFFF) on the second Update-Database command while trying to open the database and will lockup the Package Manager Console on every command execution thereafter (until you restart Visual Studio).
Access and multi user scenarios
Access is build for simultaneous multi user access over a network share. So this is a scenario that is explicitly supported.
#Hans Passant and #user2905764
Why dont you make it more sumpler by using this. If would greate if you wrap connection, command and reader objects inside a using statement block. See usage of using.
Update
Sorry , I saw this couple of minutes ago that, you are using Access db for Services, which is, I think completely insane. Since services are consumed by various clients at a time so it might lead to inconsistency. So, as Hans Passant suggested in his comment, kindly go for Sql Server Express or MySql like Server-Oriented database for such scenarios.
public bool DoesObjectExsist(String ID)
{
bool result=false;
try
{
String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + dbPath + "'";
string mySelectQuery = "SELECT Count(*) FROM Object WHERE ID = ?";
OleDbConnection myConnection = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
command.Parameters.AddWithValue("#id",ID);
myConnection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader();
try
{
if(reader.HasRows)
result=true;
}
finally
{
myReader.Close();
myConnection.Close();
}
}
catch (Exception e)
{
//log exception
}
return result;
}
I have been working on a c# project that connects to a access database, but a certain sequence of events causes it to crash with a AccessViolationException
The issue comes after calling a database connection using oledb in a separate form than the savefiledialog, and than calling savefiledialog1.ShowDialog()
Note: This also applies to the open file dialog.
It might be a bug in Access Database Engine 2010. Use 2007 instead.
connect.microsoft.com: oledb-operations-cause-accessviolationexception-during-savefiledialog
Codeproject: OpenFileDialog + OleDbConnection = AccessViolationException
Be sure you are using System.Data.OleDb from System.data.dll
Then try something like this:
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// Declare Command
OleDbCommand command = new OleDbCommand(YourSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
I had a similar issue, too, and this helped me:
I added "OLE DB Services=-1" in my connectionstring, now the problem is solved.
See: http://www.codeproject.com/Questions/106826/OpenFileDialog-plus-OleDbConnection-equals-AccessV.aspx SOLUTION 8