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
Related
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();
}
I already have a MySQL db.
I would like to use WPF application in C#. I created the project and wrote the connection lines without errors.
How can I be sure that the connection goes okay? this code doens't returns errors but I would check the datas from the "query" cmd.
This is the connection code:
string connectionString = "SERVER=localhost;DATABASE=dbamne;UID=root;PASSWORD=pass;";
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM table WHERE name = 'name';", connection);
connection.Open();
Basically you can check your connection using the method from example at MSDN:
// ...
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
But if you directly want execute your command you should use method ExecuteReader at command (or it async analog) like MSDN recomended:
// ...
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var command = new MySqlCommand("SELECT * FROM table WHERE name = 'name';", connection);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
/* This code shows just values from first column of your result table */
Console.WriteLine(reader[0]);
}
}
}
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();
}
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");
I have am OLEDB Connection configured in the connection managers and I want to use it in a SCRIPT. The script needs to call a stored proc and then create buffer rows. I have added the connection to the connections available to the script and this is my code.
Boolean fireagain = true;
SqlConnection conn = new SqlConnection();
conn = (SqlConnection)(Connections.Connection
.AcquireConnection(null) as SqlConnection);
SqlCommand cmd = new SqlCommand();
conn.Open();
ComponentMetaData.FireInformation(
0, "Script", "Connection Open", string.Empty, 0, ref fireagain);
cmd.Connection = conn;
cmd.CommandText = "up_FullTextParser_select" ;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Phrase", DbType.String).Value = Row.Keywords;
cmd.Parameters.AddWithValue("SpecialTerm", DbType.String).Value = "Exact match";
cmd.Parameters.AddWithValue("StopListId", DbType.Int32).Value = 0;
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
TermsBuffer.AddRow();
TermsBuffer.Term = rdr[0].ToString();
}
conn.Close();
Anyway, it seems to fail on the AcquireConnection. Am I converting this wrong? Should I be using a different way to using the connections defined outside the script?.
You cannot cast an OLEDB connection to SqlConnection object. You must use the OleDbConnection object. See the example - http://blogs.msdn.com/b/mattm/archive/2008/08/22/accessing-oledb-connection-managers-in-a-script.aspx
This MSDN example implies that you using AcquireConnection incorrectly.
You need to use a managed connection provider.
If you insist on using an OLEDB connection, you cannot use AcquireConnection but you can extract the connection string and then use it to create an OLEDB connection:
string connstr = Dts.Connections["my_OLEDB_connection"].ConnectionString;
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(connstr);
This may not work if the connection string is created via an expression of some sort.
IDTSConnectionManager100 connMgr = this.Connections.ADONetAppStaging ; //this we need to give name in connection manager in script component
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(connMgr.AcquireConnection(null));
//Read data from table or view to data table
string query = "Select top 10 * From ##AP_Stagging_Temp_ExportWODuplicates Order by 1,2,3 asc ";
// string query = "Select * From ##AP_Stagging_Temp_For_JLL_ExportWODuplicates order by 1,2,3 asc ";
SqlDataAdapter adapter = new SqlDataAdapter(query, myADONETConnection);
datatable dtExcelData = new datatable();
adapter.Fill(dtExcelData);
myADONETConnection.Close();