How to connect to MySQL database through c#? - c#

I read that I have to download this http://dev.mysql.com/downloads/mirror.php?id=13427#mirrors, but it says that I can't install it because I need .NET Framework. I already have 4.0?!

Use this link, it will work if you have VS.NET 2010 http://dev.mysql.com/downloads/connector/net/

Installer checking for .Net 3.5 or 2.0 mabey =

You should use MySQL Connector/Net 6.3.5 available at mentioned location (http://dev.mysql.com/downloads/connector/net/)

I pieced this together by copy/paste from an existing project then sanitizing it...so it's not been compiled and tested, but you get the idea. So here's some sample code to get you started:
using MySql.Data.Types;
using MySql.Data.MySqlClient;
private void Function()
{
//Set up connection, SqlHost/etc are classwide and declared elsewhere:
MySql connection = new MySqlConnection("SERVER=" + SqlHost + ";DATABASE=" + DatabaseName + ";UID=" + user + ";PASSWORD=" + password + ";pooling=false");
//Setup query:
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "your query here";
//Connect to relation system and execute query:
connection.Open();
Reader = command.ExecuteReader();
while(Reader.Read())
{
MessageBox.Show("here's a row from the query response: " + Reader[0].ToString());
}
//Clean up:
connection.Close();
Reader.Close();
}

Related

connection to oracle db gives System.TypeInitializationException' in Oracle.DataAccess.dll?

I trying to connect to an database in a little console application it works. but now i am making a restfull api for school but i am stuck on a runtime error:
System.TypeInitializationException' in Oracle.DataAccess.dll
my code end exception in my output
I tried a lot. checked if the version are correct it is al set up good i think. i am using
[HttpPost("InsertKlok")]
public IActionResult InsertKlok(Klok klkregd)
{
string constr = "Data Source=MydataSource;User Id=MyuserId;Password=Mypassword;";
var query = "Insert INTO KLOK(KLOK_ID, REDEN,INUIT) VALUES(" + klkregd.Klok_Id + ",'" + klkregd.Reden + "','" + klkregd.InUit + "')";
try
{
OracleConnection conn = new OracleConnection(constr);
OracleCommand command = new OracleCommand(query, conn);
conn.Open();
command.ExecuteNonQuery();
Console.WriteLine("Record inserted");
}
catch (Exception e)
{
Console.WriteLine(e);
}
return Ok(klkregd);
}
[Route("klok/")]
[HttpPost("AddKlok")]
public JsonResult AddKlok(Klok klkregd)
{
Console.WriteLine("In registerStudent");
KlokRegistratieAntwoord klkregdreply = new KlokRegistratieAntwoord();
KlokRegistratie.getInstance().Add(klkregd);
klkregdreply.Klok_Id = klkregdreply.Klok_Id;
klkregdreply.Reden = klkregdreply.Reden;
klkregdreply.InUit = klkregdreply.InUit;
return Json(klkregdreply);
}
}
}
`
In my console application i have same code and file for oracle connection but its not working here pls can someone help me
Since you use .net core you can try Oracle.ManagedDataAccess.Core instead of
Oracle.DataAccess; quotation:
Oracle Data Provider for .NET (ODP.NET) Core is an ADO.NET driver that
provides fast data access from Microsoft .NET Core clients to Oracle
databases. ODP.NET Core consists of a single 100% managed code
dynamic-link library
(bold is mine). You can get the assembly via Nuget:
https://www.nuget.org/packages/Oracle.ManagedDataAccess.Core/
Please, have a look at the tutorial from Oracle as well:
https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/ODPNET_Core_get_started/index.html

How to restore SQL Server backups using asp.net and C#?

How to restore SQL Server backup using C#?
try
{
string test = "D:\\backupdb\\05012017_130700.Bak";
sqlcmd = new SqlCommand("Restore database EmpolyeeTable from disk='D:\\backupdb\\05012017_130700.Bak'", con);
sqlcmd.ExecuteNonQuery();
Response.Write("restore database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}
Quite weird requerement you have right there. I´ve never heard of someone restoring a database backup from a webpage, and as #Alex K. told, it would be quite rare that the user that uses your web application have the required previleges.
Anyway, supposing that everything told above is OK, the code to restore a backup would be this:
Use this:
using System.Data;
using System.Data.SqlClient;
Code:
private void TakeBackup()
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "RESTORE DATABASE AdventureWorks FROM DISK = 'C:\AdventureWorks.BAK' WITH REPLACE GO";
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}
This is going to work specifically for the problem you posted. Be sure to set all the parameters of your database server on the connection string, it seems from the comments on your question that you are having communication issues. You have to solve that problems before you do anything. Some tips for that:
Be sure you set all the parameters on connection string the right way
Try to connect using another tool like ODBC so you can test all parameters
Check out SQL Network settings to see if TCP/IP is enabled

Execute ObdcCommand for NetezzaSQL with C#

I am trying to execute a command with OdbcCommand in c# but it seems i can't even open the connection. This is the data I got to create the Connection String
Server: APPRDNETEZZA (192.168.0.64)
Web Server: beamprdwb3
ODBC DSN Name (64bit): NZ_FUTUREBRANDS
User: MSTR_ADMIN
Port: 5480
This is my code
string connetionString = null;
OdbcConnection cnn;
OdbcCommand cmd;
string sql = null;
connetionString = "Driver={NetezzaSQL}; servername=APPRDNETEZZA ;
database=NZ_FUTUREBRANDS; port=5480; username=MSTR_ADMIN;
password=mstr17Uz1%4;";
sql = "CREATE EXTERNAL TABLE X_STORE_GROUP_GUID_12345(" +
"STORE_ID VARCHAR(10)," +
"STORE_NAME VARCHAR(50)," +
"USERID Varchar(255)," +
"import_guid Varchar(255), )" +
"USING(" +"DATAOBJECT('/apnas01/vol2.nfs.Data/ap_prod/data/store_upload/scripts/12345_guid_12345')" + "logDir '/apps/ap_prod/log'" + " delimiter ','" + " "; ";
cnn = new OdbcConnection(connetionString);
try
{
cnn.Open();
Console.WriteLine("Connection Opened ");
cmd = new OdbcCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
result = "Executed sucessfully";
}
catch (Exception ex)
{
result = "Error" + ex.InnerException.ToString();
}
The error happens when it tries to open the connection. While debugging it gave me this inner exception
[ODBC Driver Manager] Data source name not found and no default driver
specified
I have the Odbc driver installed in my machine. I dont know it this is happening cuz the connection string is in bad format. I have spent many hours trying to figure it out why doesnt work. Appreciate any kind of help. Thanks
Here is an example Netezza ODBC connection string:
https://www.connectionstrings.com/netezzasql-odbc-driver/
Driver={NetezzaSQL};servername=myServerAddress;port=myPortNumber;
database=myDataBase;username=myUsername;password=myPassword;
Your connection string basically looks the same:
connetionString = "Driver={NetezzaSQL}; servername=APPRDNETEZZA ;
database=NZ_FUTUREBRANDS; port=5480; username=MSTR_ADMIN;
password=xyz;";
SUGGESTIONS:
Make the entire connection string (everything inside the quotes) ONE LINE. Don't break the string into separate lines.
Or use "+" (like you did with your SQL string).
Copy the driver (nsqlodbc.dll?) into the same directory as your .exe assembly (path issue?)
Try both the 32-bit and 64-bit drivers (CPU platform issue?)
Definitely post back what you find!

Connecting to iseries DB2 database with .NET

I've been having some difficulty connecting to an iseries DB2 database from a .net 4.0 application I'm developing. I've been trying to use the IBM.Data.DB2.dll library to connect to it using the following code;
String connectionString = "Database=[DBName];UserID=[UserID];Password=[Password];Server=[ServerName]";
connection = new DB2Connection(connectionString);
connection.Open();
When the connection.Open() command is run I receive the following error:
ERROR [58009] [IBM] SQL30020N Execution of the command or SQL
statement failed because of a syntax error in the communication data
stream that will affect the successful execution of subsequent
commands and SQL statements: Reason Code "0x124C"("0100")"".
SQLSTATE=58009
Does anyone know of another way of connecting to this kind of database in .net?
This works for me:
class Program
{
static void Main(string[] args)
{
string connString = "DataSource=SYSTEM;UserID=USER;Password=PASSWORD";
iDB2Connection conn = new iDB2Connection(connString);
conn.Open();
string cmdString = "CRTPF FILE(TESTLIB/TESTNET) RCDLEN(100)";
string cmdText = "CALL QSYS.QCMDEXC('" + cmdString + "', " + cmdString.Length.ToString("0000000000") + ".00000" + ")";
iDB2Command cmd = new iDB2Command(cmdText, conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
}
}
We are using Data Direct DB2 driver from Progress. This supports Entity Framework. May be you can try with that. You can download the evaluation version online (progress.com)

Connection String for MySQL (C# in asp.net)

I am using a the C# ODBC object in asp.net to connect up to a MySQL server hosted on another computer (on the same network).
<%# Import Namespace="System.Data.Odbc" %>
<html>
<body>
<script language="C#" runat="server">
protected void Page_Load(Object Src, EventArgs E)
{
try
{
using(OdbcConnection connection = new OdbcConnection("DRIVER={MySQL ODBC 5.51.30 Driver};Database=test;Server=192.168.1.109;UID=Username;PWD=Password;"))
{
connection.Open();
using(OdbcCommand command = new OdbcCommand("SELECT * FROM tablename", connection))
using(OdbcDataReader dr = command.ExecuteReader())
{
while(dr.Read())
Response.Write(dr["name"].ToString() + "<br>");
dr.Close();
}
connection.Close();
}
}
catch(Exception ex)
{
Response.Write("An error occurred: " + ex.Message);
}
}
</script>
</body>
</html>
I am currently getting this error when I run the code:
An error occurred: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I am hosting this on a Microsoft IIS server, with ASP.net enabled. Would I be able to get any help with fixing this error?
Link to image of my MySQL server: http://i.stack.imgur.com/4NYCr.png
Would I be able to get any help with fixing this error?
Yes, you would. So, your only question was answered. And now? Please think a little more about WHAT you ask.
TO your problem.
Like always, http://www.connectionstrings.com/ is the primary resource for this ;) Anything you ever wanted to know about connectionstrings on one place.
For MySQL (asuming 5.2) you can find (for ODBC) the solution at:
http://www.connectionstrings.com/mysql-connector-odbc-5-2/
Now, your string looks good - so I start assuming you have a driver problem. I would assume that wherever you run it it just does not have - the ODBC ddriver installed.
THAT SAID: there is no real reason to use ODBC (which has native prerequisites) and not a (managed) MySQL Driver?
if you really miss the ODBC driver, you can ind the downloads at http://www.mysql.com/products/connector/. But I would really not use ODBC here - not with a native connector available.
I think you better use MySQlConnection as well as MyqlCommand for your needs:
eg:
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);

Categories

Resources