UWP connection string - c#

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).

Related

How to use a database connection class in my entire application

I have created a class for the MS Access database connection. It works fine on the majority of the forms within my Winforms app. However, I have a form where the user can add, edit or delete information from the database. I've constructed that part using a string, but when I remove the long database connection string I had there before and replace it with the class I created it throws an exception.
I've tried changing the code by removing the string, but I want to use the string method.
This is the code I have for the delete button click event
string con = (#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb");
string Query = "delete from Employees2 where EmployeeName = '" +
this.txtAdminFEmployee.Text + "' ; ";
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OleDbDataReader reader;
try
{
ConnectionString.Open();
reader = command.ExecuteReader();
DialogResult result = MessageBox.Show("Employee Deleted Successfully",
"Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
while (reader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
ConnectionString.Close();
This is the database class I created
using System.Data.OleDb;
namespace AppName
{
class OledbConnect
{
public OleDbConnection con;
public void Connection()
{
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DatabaseName.accdb");
}
}
}
I need to know how to use the database class in that string. I've tried different ways but nothing works. I am still new to c# and Google is not really returning anything I can use. Thanks
Your initial code works, but confusion is evident in the naming of variables.
string con = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb";
(I've taken the un-needed parentheses off the declaration; it's just a string.)
Calling that string 'con' is a bit confusing. I'd call it 'connectionString', or maybe 'cs' for short.
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OK, so you correctly create an OleDbConnection, passing the connection string (con) to its constructor. This is good. But you confusingly call it ConnectionString. It isn't the connection string; it's the connection, and your code thereafter uses it correctly.
So that works. Confusing for a human to read because of the mis-naming of variables, but the compiler doesn't care what their names are - it knows very well that ConectionString is an OleDbConnection and doesn't feel any of the cognitive dissonance that I do when I look at it.
If you rename the variables in the original code as I've suggested, and then copy that code into your class (BTW, I'd just call it DbConnection; it's current name is very close to another class name which might also be confusing), paying attention to what each statement does and what each variable represents then you should be good to go.

Connecting to mysql on 000webhost using C#

Im simply just trying to read what there is in the batabase on to a console but i always get an exception on the conn.Open() line. Here is all the code:
SqlConnectionStringBuilder conn_string = new SqlConnectionStringBuilder();
conn_string.DataSource = "mysql14.000webhost.com"; // Server
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxx";
conn_string.InitialCatalog = "a7709578_codecal"; // Database name
SqlConnection conn = new SqlConnection(conn_string.ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("Select name FROM Users");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1));
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
You need to build the connection string manually or use MySqlConnectionStringBuilder. MySql uses a different format than SQL Server and the SqlConnectionStringBuilder that you're using. You also need to use a MySQL library, SqlConnection, SqlCommand, etc are all build specifically for SQL Server.
MySQL connectors
For MySQL database you are using wrong provider. Those classes you have used in posted code are for SQL Server. Your code should look like below with MySQL provider related classes
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql14.000webhost.com";
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxxxx";
conn_string.Database = "a7709578_codecal";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
Check Related post in SO
Also to point out, you are selecting only one column from your table as can be seen
new SqlCommand("Select name FROM Users");
Whereas trying to retrieve two column value, which is not correct
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1))
000webhost free servers does not allow external connections to the server database.
You can only use your database from your PHP scripts stored on the server.
You can get data from database using PHP and it will return.So i advice to you using php from C# like api.

How can commit data update in Microsoft SQL sever?

In a web app, I am using SQL server. However, when I try to store some bulk amount of data, it misses some of the records and does not insert them into the database. I want to know whether there is any commit statement or synchronization for the database? Data is being sent object by object using an ajax call.
Here is my code:
try
{
int surah = Convert.ToInt32(Request["surah"]);
string verse = Request["data"];
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\PEACE_QURAN.MDF;Integrated Security=True";
System.Data.SqlClient.SqlConnection connection = new SqlConnection(connectionString);
string query = "insert into Ayyat_Translation_Language_old_20131209 values(null,null,"+surah+",'"+verse+"')";
SqlCommand cmd = new SqlCommand(query, connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch(Exception e){
System.IO.StreamWriter file = new System.IO.StreamWriter(#"E:\Office_Work\Peace_Quran\Peace_Quran\Files\ExceptionFile.txt", true);
file.WriteLine("exception details : "+e.ToString());
file.Close();
}
As you understand, the records cannot get lost in the way. Either the INSERT statement would execute, or you would get an exception. Since neither is happening, I believe that you loose something in the request generating mechanism.
I would strongly suggest to put some logging message on each request. You will probably find out that your requests are less than you thought. This could be for a number of reasons, but since I don't know the exact mechanism calling the server side code, I cannot have an opinion.
Hope I helped!

Access db, check if someone is using... (OLEDB/C#)

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.

.Net C# how to connect to external SQL Server database ? OleDb or other?

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.

Categories