This question already has answers here:
How to connect to MySQL Database?
(6 answers)
Closed 3 years ago.
What should I do to connect to MySql?
string constr = "Data Source=steve-pc;Initial Catalog=itcast2014;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
string sql = "select count(*) from TblPerson";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
//object count = (int)cmd.ExecuteScalar();
object count = Convert.ToInt32(cmd.ExecuteScalar());
Console.WriteLine("TblPerson表中共有{0}条数据。", count);
}
}
You will have to install package for mysql data. Once you have that installed and added references, you can do it like this :
string server = "steve-pc";
string database = "itcast2014";
string username = "YourMysqlUsername";
string password = "YourMysqlPassword";
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}",server, database, username, password);
using(var connection = new MySqlConnection(connstring);
{
connection.Open();
string query = "select count(*) from TblPerson";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string personsCount = reader.GetString(0);
Console.WriteLine(personsCount);
}
connection.Close();
}
More detailed and better answer for this is on How to connect to MySQL Database?
Install Oracle's MySql.Data NuGet package, to add it as a package and it is the easiest way to do. You don't need anything else to work with MySQL database.
Or you can run below command in Package Manager Console
PM> Install-Package MySql.Data
and this answer could help you: How to connect to MySQL Database?
Related
How can I connect a SQL database in C#?
My code:
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
var conn = new SqlConnection(connectionString);
conn.Open();
conn.Close();
I get: Error: 40 - could not open a connection to sql server. I tried also in Python and it worked well:
cnx = mysql.connector.connect(user='root', password='MyPassword', host='127.0.0.1', database='MyDatabase')
cursor = cnx.cursor()
What am I missing in C#?
Please use MySqlConnection for MySql DB.
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
MySqlConnection conn = new MySqlConnection(connectionString );
conn.Open();
string sqlcommand = "SELECT Query";
MySqlCommand cmd = new MySqlCommand(sqlcommand , conn);
please follow this example
using MySql.Data.MySqlClient;
var connectionString = "server=serveradress;database=dbName;user id=sqluser;password=abc;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
using var command = new MySqlCommand("SELECT COUNT(*) FROM tableName ", connection);
var Count = command.ExecuteScalar();
Console.WriteLine($"There are {Count } movies");
}
server adress in general is 127.0.0.1 ,if you are working locally
here the source page :
example
and also consider reading this page here docs
I'm trying to do a parametrized Insert query in C#, console application. DB = MYSQL 8.
StringBuilder commandString = new StringBuilder("INSERT INTO testtable (testcol) VALUES ");
string testparam = "testvalue";
commandString.Append(string.Format("('{0}')", testparam));
commandString.Append(";");
string ConnString = "server = localhost; database = xxxxx; User = xxxxx; Password = xxxxx; port = 3306";
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = ConnString;
conn.Open();
Console.WriteLine(commandString); //if I copy the commandstring from the console and into Mysql workbench it works.
using (MySqlCommand cmd = new MySqlCommand("#str", conn))
{
cmd.Parameters.Add("#str",MySqlDbType.Text).Value=commandString.ToString();
cmd.ExecuteNonQuery();
}
Everything looks good, commandString is ok: INSERT INTO testtable (testcol) VALUES ('testvalue');
I get an exception stating the following:
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''INSERT INTO testtable (testcol) VALUES (\'testvalue\');'' at line 1'
Please note the escape slashes in the message around 'testvalue'. I did not put them there and they do not show up in the commandstring prior to this line. Is this causing the error? And If so, why?
If I use cmd.Parameters.AddWithValue, I get the same working commandstring, but an error: System.FormatException: 'Input string was not in a correct format.' However if I copy paste the generated commandstring from the debugger to MySQL workbennch and execute it, it works.
You aren't using parameterised queries correctly, you shouldn't covert the entire SQL string into a parameter as you do here:
using (MySqlCommand cmd = new MySqlCommand("#str", conn))
{
cmd.Parameters.Add("#str",MySqlDbType.Text).Value=commandString.ToString();
cmd.ExecuteNonQuery();
}
It doesn't do a straight text replacement, and you are in fact making things a bit more complicated than they need to be. An example might be:
string ConnString = "server = localhost; database = xxxxx; User = xxxxx; Password = xxxxx; port = 3306";
string testparam = "testvalue"; // realistically this might come from user input
string sql = "INSERT INTO testtable (testcol) VALUES (#testcol)";
using (var conn = new MySqlConnection(ConnString))
using (var cmd = new MySqlCommand(sql, conn))
{
conn.Open();
cmd.Parameters.Add("#testcol", MySqlDbType.Text).Value = testparam;
cmd.ExecuteNonQuery();
}
how do i connect to Mysql database using c#?
i have this code
entstring MyConnection = "server=localhost; port=3306; databae=database_name; uid=root;pwd=;sslMode=None; ;
First download MySql.Data package from nuget package manager then add namespace
//Add MySql Library
using MySql.Data.MySqlClient;
Connection Code-
string connString = "server=server;user=user;database=db;password=*****;";
MySqlConnection con = new MySqlConnection(connString);
this is an idea .
string MyConnection = "server=localhost; port=3306; databae=database_name; uid=root;pwd=;sslMode=None; ;
string Query = "INSERT INTO table_name(username,password)VALUES('"+textbox_name.Text+"','"+password_name.Password+"');
MySqlConnection con = new MySqlConnection(MyConnection);
MySqlCommand command = new MySqlCommand(Query,con);
con.open();
try{
command.ExcuteNonQuery();
}
catch(Expection ex)
{
MessageDialog box = new MessageDialog(ex.ToString());
box.ShowAsync();
}
con.close();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Stored procedure return into DataSet in C# .Net
How can I call a stored procedure from my project using C#? I need to get the output of that stored procedure into a data table but I'm getting an error.
Code:
private string connectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;Integrated Security=SSPI;Initial Catalog=blablalbla;";
private DataTable dtProductPrijsActueel = new DataTable();
public DataTable productPrijsActueel()
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "procSelectPrijsActueel";
dtProductPrijsActueel.Load(comm.ExecuteReader());
conn.Close();
conn.Dispose();
return dtProductPrijsActueel;
}
Error:
ERROR : KEYWORD NOT SUPPORTED : 'PROVIDER'
This is really something that should've just been googled, but the general code you're looking for looks something like this:
string connect = System.Configuration.ConfigurationManager.AppSettings["conn"];
SqlConnection connection = new SqlConnection(connect);
string spName = "TheSpName";
SqlCommand spCmd = new SqlCommand(spName, connection);
spCmd.CommandType = CommandType.StoredProcedure;
spCmd.Parameters.Add("#SomeParam", SqlDbType.String).Value = "Some Parameter";
connection.Open();
var dataTableReader = spCmd.ExecuteReader();
I want to use ORACLE DBMS feature in my C# application to compile all the invalid objects but I received below error. would you please help me how I can run below script in C#:
"exec dbms_utility.compile_schema('"+schema+"');";
my function :
internal void compileAllInvalideObject(string userId, string password, string schema)
{
//OracleConnection con = new OracleConnection();
string connectionString = "provider=MSDAORA;data source="+userId+";user id="+userId+";password="+password;
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
myOleDbCommand.CommandText = "exec dbms_utility.compile_schema('"+schema+"');";
myOleDbConnection.Open();
myOleDbCommand.ExecuteNonQuery();
myOleDbConnection.Close();
}
error:
ORA-00900: invalid SQL statement
I am using oracle 9i.
Actually dbms_utility.compile_schema act same as store procedure so we can not call it in same way which we run a query, we need to write program in such way we call a store procedure.
OracleConnection con = new OracleConnection();
//using connection string attributes to connect to Oracle Database
con.ConnectionString = "User Id="+userId+";Password="+password+";Data Source="+schema;
OracleCommand ocb = new OracleCommand("dbms_utility.compile_schema", con);
ocb.CommandType = CommandType.StoredProcedure;
ocb.Parameters.Add(new OracleParameter("#schema", userId));
con.Open();
ocb.ExecuteNonQuery();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
Console.WriteLine("Disconnected");