How to open a MySql connection with TextBox inputs in C# - c#

What I want to do is have text boxes for the user to input the required fields for the connection to the MySQL table, Here is the code I currently have.
public partial class Form1 : Form
{
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = serverTextBox.Text;
conn_string.UserID = userTextBox.Text;
conn_string.Password = passwordtextBox.Text;
conn_string.Database = dataBaseTextBox.Text;
using (MySqlConnection mcon = new MySqlConnection(conn_String.ToString()));
MySqlCommand mcd;
MySqlDataAdapter mda;
//-----open connection-----//
public void openCon()
{
if (mcon.State == ConnectionState.Closed)
{
mcon.Open();
}
}
//-----close connection-----//
public void closeCon()
{
if (mcon.State == ConnectionState.Open)
{
mcon.Close();
}
}
}
I really have no idea how to setup a MySQL connection properly and this was my (failed) best guess.
here is a new picture that might help http://prntscr.com/bgubj5

There should be a lot of reasons of Your problem. You posted only small piece of code, which is not enaught. If You want to connect do database consider following steps:
-make proper connection string (it depends on the database)
-connection string can be make from user inputs, but must be known before calling MySqlConnection
so, firstly save the user inputs to variable, make connectionstring of them, and finally pass it to MySqlConnection constructor
PS. this would help with making connectionstring: https://www.connectionstrings.com/

What exceptions does it throw?
Build the connection string first. Set a breakpoint and check if it looks good.
Or an even better approach will be to use the MySqlConnectionStringBuilder object
your code will look like this:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = serverTextBox.Text;
conn_string.UserID = userTextBox.Text;
conn_string.Password = passwordtextBox.Text;
conn_string.Database = dataBaseTextBox.Text;
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{
//query whatever you want, be aware of SQL injection
}

Related

MySQL insert C# fails when Connection Pooling is activated

I have the following INSERT method in a C# web project. If I run the project without MySQL connection poling everything works fine, but when I activate Pooling=True in the DB connection string this method stops working, the insert statements never complete.
I realized how to modify the code to make it work, but I would like to understand what is happening and I hope you could help.
When I comment line //myR.Close(); everything works fine.
using MySql.Data.MySqlClient;
//query example consulta="INSERT INTO users (id, name) VALUES (1, 'Rob');
public static MySqlConnection GetWriteConnection()
{
string connStr = MySqlConnectionStrings.WriteConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static MySqlConnection GetReadConnection()
{
string connStr = MySqlConnectionStrings.ReadConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static bool Insert(string consulta)
{
MySqlConnection conn = BdaHelper.GetWriteConnection();
conn.Open();
using (conn)
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
MySqlCommand micomando = new MySqlCommand(consulta, conn);
micomando.ExecuteNonQuery(); //still not working
return true;
}
catch (Exception ex)
{
return false;
}
}
}
My app has also multi-thread concurrency and two types of database connections, one specifically for only-read purposes and other different for write. When an insert statement fails I don't get any error simply the change doesn't commit in the database. Reading the article in the comments I don't think this applies to this issue but I would add an example of my main program:
MySqlConnection readConnection = BdaHelper.GetReadConnection();
using (readConnection)
{
var users = GetUsers(readConnection);
var credentials = GetCredentials(readConnection);
//Example is the query that fails don't giving any exception
Insert("INSERT INTO login_log (id_user, date) VALUES (1, now())");
}
May the problem be caused because there are two concurrent connections?
I shouldn't reuse read connection, even is a different connection than the write connection?

How do I connect to a Local MSSQL Database

EDIT: I've just tested it in ASP.NET and it works perfectly fine. So no issue with the connection string or anything. Guess Unity doesn't like this method? Maybe there's some more DLL's I need to copy? Any ideas?
So I'm making a game in Unity and I'm trying to use the System.Data.SqlClient library to connect to some stored procedures I have made for things such as registering a user.
I have copied the System.Data.dll from "C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity" and that has all worked fine.
I'm currently using this connection string, which works fine on an ASP.NET application but just using a different mdf:
private string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf';Integrated Security = True";
The problem occurs when running this code:
using System.Data.SqlClient;
using System.IO;
public void Login()
{
Crypto crypto = new Crypto();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
} catch (Exception e)
{
Debug.Log(e);
}
SqlCommand command = new SqlCommand("USERS_LOGIN_USER", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Username", usernameInputField.text));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (crypto.EncryptString(passwordInputField.text) == reader["password"].ToString())
{
UserAccountManager.instance.userInfo = FetchUserInfo((int)reader["id"]);
}
}
}
}
The problem happens on the line "conn.Open()", where Unity gives me the error:
System.Net.Sockets.SocketException: No such host is known.
Furthermore, without the try catch, the error occurs where I create a new SqlDataReader, where I get this issue:
InvalidOperationException: ExecuteReader requires an open connection to continue. This connection is closed.
I understand that this is an issue with the connection, in that it's not running or the connection isn't working properly, however I can't seem to find a solution and I have a sneaky suspicion that it's something to do with Unity not supporting this library.
Some more clarification just before I end off:
The user enters their credentials into the "usernameInputField" and "passwordInputField"
The user presses Login, which runs the "Login" method shown above
The error occurs.
If any more information is required please leave a comment.
Thanks!
What is the scope of connectionString? Do you need to pass the connectionString to the Login() function?
public void Login(string connectionString)
I am a DBA, not a .Net developer, so forgive me if my questions are too basic or if my .Net syntax is wrong.
You can try this
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog ='C:\USERS\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf'; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = True; ApplicationIntent = ReadWrite; MultiSubnetFailover = False"
SqlConnection con = new SqlConnection();
if (con.State==ConnectionState.Open)
{
con.Close();
con.ConnectionString = connectionString;
con.Open();
cmd.Connection = con;
}
else
{
con.ConnectionString = connectionString;
con.Open();
cmd.Connection = con;
}

How do I create a class with SQL connection and query functions and calling it to my windows form buttons?

I want to create a class that has SQL connection and functions (like insert, select, delete queries) and I want to call it to my forms (buttons and etc.)
I don't know if it's possible or not or maybe there are some ways on doing this so...
I've done some research and come up with this code on class SQL connection and I'm not sure if it's correct.
Thank you very much in advance. I'm a beginner and want to learn more on c#.
Any type of response is appreciated. Thank you
Sorry for my bad English
using System.Data.SqlClient;
class SqlConnClass
{
public static SqlConnection GetConnection()
{
string str = "Data Source=localhost;Initial Catalog=kwem;Integrated Security=True;";
SqlConnection conn = new SqlConnection(str);
conn.Open();
return conn;
}
You were close! You may want to take the `conn.Open()' out of your method as you can open it for your query. (Remember to close it or put it in a using statement!)
public static void UpdateDB(string valToUpdate)
{
SQLConnection conn = GetConnection();
using (conn)
{
SQLCommand updateCommand = new SQLCommand(GetConnection(), "Update Table
Set Val = #newValue");
updateCommand.Parameters.AddWithValue("#newValue", valToUpdate);
conn.Open();
updateCommand.ExecuteNonQuery();
}
}
You would then do the same for any other kind of DB functions.
It's true but; if your string str do not work. Please try this:
string str = "Data Source=local host ;Initial Catalog=kwem;Integrated Security=True"
also you need to define sql table and then select your database.
You are on the right path.
What you are referring to is called a data access layer, or DAL for short.
It's a part of the n-tier architecture model (in the simple version there are 3 tiers - presentation, business logic and data access layer).
The basic concept is that you separate the presentation, logic and data into 3 different parts of the application.
As for the data access layer, usually you'll have a static or singleton class responsible to connect the business layer to the data. This class will contain methods for CRUD operations - Create, Read, Update and Delete data. You will need to create methods for each operation and for each data entity.
One approach I see all the time is this:
public static class DAL
{
private static string _ConnectionString = null;
static DAL() // A static constructor to initialize the connection string
{
_ConnectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
}
public static DataSet GetCategories()
{
var ds = new DataSet();
var sql = "SELECT * FROM Categories";
using (var con = new SqlConnection(_ConnectionString))
{
using (var cmd = new SqlCommand(sql, con))
{
using (var adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
}
}
}
return ds;
}
public static int DeleteCategory(int categoryId)
{
int rowsEffected = 0;
var sql = "DELETE FROM Categories WHERE Id = #Id";
using (var con = new SqlConnection(_ConnectionString))
{
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = categoryId;
con.Open();
cmd.ExecuteNonQuery();
}
}
return rowsEffected;
}
}
and so on. As you can see, there is a lot of code that repeats itself.
This means longer code, herder maintenance, and if for some reason you will want to support other types of databases (like migrating to MySql, Oracle or whatever) You will have to work very hard to change all the vendor specific classes in your DAL (SqlConnection, SqlCommand etc`).
These problems are exactly the reason I wrote ADONETHelper. I've been using it for a few years (mostly in earlier, different forms) and I feel now it's matured enough to go public. It's currently under MIT licence, meaning it's completely free and you can download your copy and change it as you see fit.
Should you choose to use it, your DAL class should probably look like this:
public static class DAL
{
private static IDBHelper _DB;
static DAL() // A static constructor to initialize _DB
{
// initialize connection string from config file
var connectionstring = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
_DB = DBHelperFactory.GetInstance(DataBaseType.SQLServer, connectionstring);
}
public static DataSet GetCategories()
{
var sql = "SELECT * FROM Categories";
return _DB.FillDataSet(sql, CommandType.Text);
}
public static int DeleteCategory(int categoryId)
{
var sql = "DELETE FROM Categories WHERE Id = #Id";
var param = _DB.CreateParameter("#Id", ADONETType.Int, categoryId);
return _DB.ExecuteNonQuery(sql, CommandType.Text, param);
}
}
As you can see, code repetitions are down to the bare minimum, and migrating to a different database is as simple as changing the static constructor to use a different DataBaseType. Of course, if you are using vendor-specific sql you will have to change that too.

SqlConnection State is always Closed at Execution

I am trying to make a simple MS Access Database connection by using the SqlConnection and SqlCommand objects.
As you can see here is how I make the connection:
private SqlConnection GetConnection()
{
String connStr = ConfigurationManager.ConnectionStrings[0].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
return conn;
}
And before you ask, yes I have tried to move this piece of code to the method that calls it. Didn't change anything. It still reads the connection string wrong.
The connection string looks like this and is located in the App.config file:
<add name="ConnString" connectionString="Server=*.*.*.*;Database=familie;User Id=mfs;Password=********;"/>
But when I get this error:
And look at the connection string object at the time, the string looks like this:
"data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
I have spent about 2 hours now trying to make this work, going to many different sites to figure out what I did wrong, but I either get information is that is too old, conflicting or deals with connecting to a local database, when this is in fact an external one access through a proxy that was given to me by my client (TrustGate if anyone should ask)
The method that calls GetConnection() looks like this:
public Dictionary<int,String> GetPostNrList()
{
SqlConnection conn = GetConnection();
SqlCommand cmd = new SqlCommand("Execute dbo.HENT_POST_NR_LISTE", conn);
var reader = cmd.ExecuteReader();
Dictionary<int, String> liste = new Dictionary<int, string>();
while (reader.NextResult())
{
int post_nr = (int) reader.GetSqlInt32(0);
String by = reader.GetString(1);
liste.Add(post_nr, by);
}
CloseConnection(conn);
return liste;
}
What exactly am I doing wrong?
The exception message tells you exactly what the problem is - your connection is not open. You just need to open the connection prior to executing a command:
conn.Open();
BTW, a good pattern is to using a using block when dealing with SQL connections, to ensure it gets disposed properly:
using (var conn = GetConnection())
{
using (var comm = xxxxxxx)
{
conn.Open();
using (var rdr = comm.ExecuteReader())
{
// xxxxx
}
}
}
You don't have to specifically close anything - the using pattern does all that for you.

how to update data from table using C#.net

I've a form opened which is has loaded some sort of data (like username, CNIC, Contact no, etc etc) in Check boxes, now I want to update the data in such manner that I simply change the text in the text boxes and click on the save changes to save it. I've tried it but I am not able to do it in correct manner.
Let me show you how I've coded, the code I did in frmViewformList savechanges button is :
private void btnSaveChanges_Click(object sender, EventArgs e)
{
string sql;
string UserName;
UserName = txtUserName.Text; // saving data loaded on run time to UserName
sql = "";
sql += "UPDATE UserLogin";
sql += "SET Name = "+ //how to access data I've changed in TextBox after loading +"";
sql += "WHERE Name= " + //how to access data which was in text box right after loading + ""; //
}
I am a bit confused about how to refer to data, like the name already in the text box or the name which I have changed and how to write it in SQL query...
This question is a bit confusing, I know. Let me explain; the form is loaded, there are text boxes which is being populated with the data in database on load event, I change the data in text boxes and save on click so that the update query runs and changes the data in database as well.
I'm not able to create logic here how to do this, can any one help me out, I am sorry I am a new developer of C# that's why I am a bit confused.
You should use Sql Parameters in order to avoid SQL Injection which could leave your database vulnerable to malicious exploitation.
It's a good idea to separate the logic for performing the update to the logic where you create your query so you don't have to repeat code and so that you can maintain your code easier.
Here is an example you can reference:
public void DoWork()
{
// Build Query Use #Name Parameters instead of direct values to prevent SQL Injection
StringBuilder sql = new StringBuilder();
sql.Append("UPDATE UserLogin");
sql.Append("SET Name = #UpdatedName");
sql.Append("WHERE Name = #Name");
// Create parameters with the value you want to pass to SQL
SqlParameter name = new SqlParameter("#Name", "whatEverOldNameWas");
SqlParameter updatedName = new SqlParameter("#UpdatedName", txtUserName.Text);
Update(sql.ToString(), new [] { name, updatedName });
}
private static readonly string connectionString = "Your connection string"
private static readonly DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
public static int Update(string sql, SqlParameter[] parameters)
{
try
{
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
foreach (var parameter in parameters)
{
if (parameter != null)
command.Parameters.Add(parameter);
}
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch (Exception)
{
throw;
}
}
You will want to strip all ', ", and ` characters out of your input so that people can't inject SQL. When you do SET Name = " +, you'll want to actually wrap whatever you're including in quotes because it's a string: SET Name = '" + UserName "' " +...
This is probably best done using
string.Format("UPDATE UserLogin SET Name = '{0}' WHERE Name = '{1}'", UserName, FormerUserName);
Then you will execute your query by using System.Data.SqlClient; and then work with SqlConnection to establish a connection to the server, and execute a SqlCommand of some kind; take a look at: http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
The following is a code snippet to insert data into database using ADO.NET and assuming SQL Server database.
At the top of your .cs file you should have.
using System.Data.SqlClient; // for sql server for other data bases you should use OleClient instead.
And inside your button click event you could put the following.
// to know how to get the right connection string please check this site: http://www.connectionstrings.com
string connString = "database connection string here";
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
//insert text into db
string sql_insert = "INSERT INTO ....."; // Use parameters here.
SqlCommand cmd_insert = new SqlCommand(sql_insert, con);
int rowsAffected = cmd_insert.ExecuteNonQuery();
}
Hopefully this is enough to get you started.

Categories

Resources