I have a problem with a threaded Client/Server application, I have a serversid that has a Access DB, and with one thread for each client, but I get a problem if both client threads asks to open the DB at the same time. Is there any way to check if the DB is in use (I know I can have a varible and keep controlling/setting that, but would like to avoid that. Here is an example connection
String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + dbPath + "'";
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand command;
connection.Open();
command = new OleDbCommand("UPDATE Client SET Online = " + online)
command.ExecuteNonQuery();
connection.Close();
Would really like some help!
/Nick
Per this http://www.connectionstrings.com/access-2007 you can set Exclusive=1 in connection string to grant that only one connection can use this database. All another trying will fail.
Related
I want to create a connection for my UWP and database. I want the uwp to send a value to the database.
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1; uid = root;" + "pwd=root;database=test";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
}
Is this the correct way to write the connection ? and where do I write this part of the coding at ?
enter image description here
Main page or any of my other page ? (scenario 1-3)
Your content looks right, I would try to use 'localhost' rather than ip.
var myConnection = new MySqlConnection();
myConnection.ConnectionString = "database=test;server=localhost;uid=root;pwd=root";
myConnection.Open();
More info see: https://dev.mysql.com/doc/dev/connector-net/6.10/html/P_MySql_Data_MySqlClient_MySqlConnection_ConnectionString.htm
I would also check here to see if you are providing enough info, which you are. https://www.connectionstrings.com/mysql/
In terms of connecting to the database, it depends. What type of application is this? Typically, database connections are made during the start of the application. If you are using Entity Framework, you'll want your Database Context to manage the connection (which is an entirely different topic).
I'm having an issue when connecting to a remote host. I am able to connect to my local server with a copy of the database.
I'm trying to connect to the XenForo DB on my web host and get some information. All is working on localhost.
private static MySqlConnection _connection =
new MySqlConnection("Server=ip; database=ls-v_forum; UID=ls-v_forum; password=pass");
public static int? FetchUserId(string emailoruser)
{
MySqlCommand userCommand = new MySqlCommand("SELECT * FROM xf_user WHERE username='" + emailoruser + "'", _connection);
MySqlCommand emailCommand = new MySqlCommand("SELECT * FROM xf_user WHERE email='" + emailoruser + "'", _connection);
_connection.OpenAsync();
}
That's the code and it's throwing this error
Connection must be valid and open.
at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
at MySql.Data.MySqlClient.MySqlCommand.CheckState()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior
behavior)
EDIT
public int? FetchUserId(string emailoruser)
{
using (var _connection = new MySqlConnection("server=ip; database=ls-v_forum; UID=ls-v_forum; password=pass"))
{
MySqlCommand userCommand = new MySqlCommand("SELECT * FROM xf_user WHERE username='" + emailoruser + "'", _connection);
MySqlCommand emailCommand = new MySqlCommand("SELECT * FROM xf_user WHERE email='" + emailoruser + "'", _connection);
_connection.Open();
MySqlDataReader userReader = userCommand.ExecuteReader();
int? userId = null;
while (userReader.Read())
{
userId = userReader.GetInt32("user_id");
}
userReader.Close();
if (userId == null || userId == 0)
{
MySqlDataReader emailReader = emailCommand.ExecuteReader();
while (emailReader.Read())
{
userId = emailReader.GetInt32("user_id");
}
emailReader.Close();
}
_connection.Close();
return userId;
}
}
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any
of the specified MySQL hosts.
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder
settings)
at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
I didn't attempt to troubleshoot your connection command, but the following works for me when connecting to a SQL DB on a remote machine
You can provide the machine name even if it is the local machine, so the code below will work if the program is running on the same machine as the database or if the program is running on one machine and the database is on another, so long as the two machines are networked AND the account you're running the program under has access to the machine and instance and database.
Please note in example below, the "default" instance name (MSSQLSERVER) was used when SQL was installed. When the DB instance name is the default name, then you must not provide an instance name explicitly (you'll get an error if you do). The only time you provide an instance name explicitly is when it is not the default instance name. The code below can handle either scenario (by setting dbInstanceName variable to "" or an instance name, e.g. "\SQLEXPRESS"). See S.O. SQL Server: How to find all localdb instance names. When it doubt, try an empty instance name and a name you believe to be the instance name to see what works.
string databaseMachineName = "machine_name";
string databaseInstanceName = "";
string dbName = "database_name";
using (SqlConnection sqlConnection = new SqlConnection("Data Source=" + databaseMachineName + databaseInstanceName + "; Initial Catalog=" + dbName + "; Integrated Security=True;Connection Timeout=10"))
{
.
.
.
}
I'm having an issue when connecting to a remote host.
Not necessarily. According to the error, the issue isn't that you can't connect. It's that you're trying to use a connection that isn't connected:
Connection must be valid and open.
Specifically where you execute a command:
MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
Which isn't in the code you're showing. However, there are a couple of fundamental mistakes that are in the code you're showing which would easily lead to an error like this:
1. Using a static shared connection object.
This is a famously bad idea. We've probably all tried it, and we've probably all run into issues exactly like this one. The underlying system is pretty efficient at creating/pooling/using/disposing database connections. Don't try to optimize for it. Instead, you should create/use/dispose your connections in as small a scope as possible. For example:
using (var connection = new MySqlConnection(SOME_CONNECTION_STRING))
{
var userCommand = new MySqlCommand(SOME_COMMAND_STRING);
// use the command, get the data you need from it
}
// leave the context of the database and return to business logic, UI, etc.
This is because keeping complex things like database connections synchronized is hard, and keeping connections open is expensive. Let the underlying system open/pool/close connections.
2. Not awaiting an async operation.
What would happen here?:
connection.OpenAsync();
userCommand.ExecuteNonQuery();
An error. Because the code didn't await the asynchronous operation, so the connection isn't open when you're trying to use it. Either don't use the asynchronous operation:
connection.Open();
userCommand.ExecuteNonQuery();
or await it:
await connection.OpenAsync();
userCommand.ExecuteNonQuery();
(And obviously make the containing method async, and its callers should await it, etc.) But definitely don't try to use a connection before it's had a chance to open.
3. (Unrelated, but still important) Your code is vulnerable to SQL injection.
SQL injection happens right here:
"SELECT * FROM xf_user WHERE username='" + emailoruser + "'"
Where did emailoruser come from? Was it user input? Was it a value pulled from data which was previously provided by a user? How trustworthy is it? What this string-concatenation approach does is allow any user to execute any SQL code they want on your database. Instead, use query parameters and treat user input as values instead of as executable code.
i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}
I'm trying to update a CLOB column in my database with a long string containing the HTML contents of an email. There are 18,000 characters in the record I'm having an issue with.
The below code will work if I set the html variable to "short string". But if I try to run the code with the long 18,000 character HTML string, I get this error: "Oracle.DataAccess.Client.OracleException ORA-22922: nonexistent LOB value ORA-02063: preceding line from ((servername))"
public static void UpdateHtmlClob(string html, string taxId,string un, string pw)
{
using (OracleConnection conn = new OracleConnection())
{
try
{
conn.ConnectionString = "User Id=" + un + ";Password=" + pw + ";Data Source=server.com;";
conn.Open();
OracleCommand cmd = new OracleCommand();
string indata = html;
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
OracleParameter clobparam = new OracleParameter("clobparam", OracleDbType.Clob, indata.Length);
clobparam.Direction = ParameterDirection.Input;
clobparam.Value = indata;
cmd.Parameters.Add(clobparam);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
conn.Close();
}
}
}
Before you edited your code to reflect my answer, there were two problems with your code that I saw.
Firstly, you need to use a colon in your command text to tell Oracle that clobparam is a bind variable, not a column name:
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
Secondly, you were not setting the database connection anywhere on the command. Which connection should the command be using? In your situation you have only one connection but more generally it may be possible to have more than one connection open. Add the line
cmd.Connection = connection;
or alternatively create the command using
OracleCommand cmd = connection.CreateCommand();
Of course, it would be nice if Oracle.DataAccess returned an error message that gave you the slightest hint that this was what you were doing wrong.
Anyway, now that you've edited your question to include the critical detail ORA-02063: preceding line from ((servername)), which tells us that you are using a database link, all I can really do is echo what I wrote in the comment: connect direct to the remote database to transfer LOB data, don't use a database link.
Hi I would like to know how I should connect to the external SQL Server database in C# , .NET ?
For example if I have there parameters :
SQL info
Url to get to database (throughout browser also): Sqlweb.companyname.com
Database username: username
Server: Dcms-xxx
Databasename: databaseName
Databasepassword: password
?
I know how to connect to internal : Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.AppDomain.CurrentDomain.BaseDirectory + "..\\Files\\MapPlaces\\Database.mdb;";
But what about external ?
I have tried :
string nowConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sqlweb.companyname.com;Initial Catalog = databaseName; User Id = Username; Password = Password;";
System.Data.OleDb.OleDbConnection dbcon = new System.Data.OleDb.OleDbConnection(nowConString);
string sql = "SELECT * FROM XXXTable";
dbcon.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbcon);
System.Data.OleDb.OleDbDataReader reader;
reader = cmd.ExecuteReader();
ScriptStuff.Append("Reader created!<br/>");
while (reader.Read())
{
string companyName = reader.GetValue(1).ToString();
ScriptStuff.Append(companyName+"<br/>");
}
Did not work ! Thank you for your help !
Edited from comments:
Yes that was one my mistake, thanks. Since first one was access and YES second is SQL Server. And it is SQL Server 2005. But I am new to .net and all that... I have found first one and second one in that connectionstring.com but I could not find or understand how to use that for this one ...
Could you help, and just post hole connection ? Thanks – Vilius 7 mins ago
I mean do I still need to use OleDB ? should there be "Provider=Microsoft.Jet.OLEDB.4.0;" in that connection string ? Where do i post what (server (that Dcms-xxx), or url of the sql server (sqlweb.companyname.com))? THANKS FOR YOUR HELP ! –
I would add a connectionString to my app/web.config.
<connectionStrings>
<add name="AspnetdbConnectionString"
connectionString="Data Source=<databaseadress>;Initial Catalog=<database>;User Id=<user>;Password=password>"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
The above example is how you specify an connectionstring for a MSSQL connection, and below a way to use this connectionstring.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AspnetdbconnectionString"].ConnectionString))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.Text;
cm.CommandText = "SELECT * FROM ...";
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read())
{
// do stuff
}
}
}
}
Are you sure that it's a SQL Server database that you are trying to connect to?
Your "internal" example connects to a Microsoft Access database (OLEDB provider and database file extension .mdb)
If your external database is really a SQL Server database, the recommended way is using SqlConnection, SqlDataReader and so on instead of OleDbConnection etc.
Or, if you really want to use OleDb, you need a different connection string.
See connectionstrings.com (for SQL Server 2008, 2005 or 2000, depending what you're trying to connect to).
I would highly recommend taking a look at:
http://www.connectionstrings.com/
It's a quick, "in you face" treatment of the subject of connection strings for all major databases.