Assigning a database value to a string in c#(.net)
actually i am making a login system so i want to know how can we assign a value read from the database to any string variable in a database?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sunny SharmaPosted Jun 4, 2013, 5:32 AM
To use MySql Database in C#, download and install MySql .NET connector from here:
http://dev.mysql.com/downloads/connector/net/
After you finish installation,add reference to MySql.Data.dll and add namespace as:
Using MySql.Data.MySqlClient;
Syntax for ConnectionString is as follows:
"Server=localhost;uid=username;password=pwd;database=test;pooling=false;"
Below is a sample code snippet which will enable you to connect and perform operations on MySql Database:
//Create and initialize the connection and command
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("select * from table", conn);
try
{
conn.Open();
}
catch(Exception ex)
{
// Database connection error;
}
if (conn.State == ConnectionState.Open) //ConnectionState Enum is contained in System.Data namespace
{
//Perform operations here
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader.GetString(0);//Here you assign the values from database to variables
}
}
if (conn.State == ConnectionState.Open)
{
try
{
conn.Close();
}
catch { }
}
----------------------------------------------------------------------------------
Happy Coding :)
Please don't forget to accept this as answer if it helps!
Thanks.
ejaz ul haqPosted Jun 4, 2013, 5:49 AM
ejaz ul haqPosted Jun 4, 2013, 5:22 AM
Sunny SharmaPosted Jun 4, 2013, 5:06 AM