I am unable to create Entity Models from database.
It is first time using MySQL from VS2017.
I am following tutorial at
1) https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-intro.html
2) https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-entity-framework-winform-data-source.html
3) https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html
I installed MySQL on local machine. I installed NuGet packages MySql.Data, MySql.Data.Entity, and MySql.Web (all version 6.9.11).
In tutorial No.2, while adding “ADO.Net Entity Data Model”, I get upto this window
I click next and then window silently close without producing any Data Models.
This means I don’t see the window below.
I assume my connection strting and web.config file is OK as I can successfully execute code bellow and get result “Samoa -- Malietoa Tanumafili II”
`
using System;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public class Tutorial2
{
public static void Main()
{
string connStr = "server=localhost;user=root;database=world;port=3306;password=******";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent='Oceania'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]+" -- "+rdr[1]);
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
}
}`
Please guide what I am doing wrong.
This is a known bug in MySQL Connector/NET: bug 89338. According to that bug report, there's a bug in the wizard code that should be fixed in the next version, 6.10.7.
Related
I have built a web api using dotnet and this is my first time using Azure (or any other cloud platform) to host web applications. I've used EntityFramework and MySQL database with to build my project.
I used DbConnectionString = "Server=localhost;Database=hms;Uid='{root-user}';Pwd={pw};" as the connection string of my SQL Database and now I'm wondering how can I connect it with the Azure SQL Database I have created. I added my IP address in firewall access in the Azure server and tried changing the connection string as DbConnectionString = "Server=server.database.windows.net:1433;Database=hms;Uid='{root-user}';Pwd={pw};" but it gives an error An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySql' call. when I'm trying to update the database after adding migrations.
I'd like to know what I have done wrong or what else I need to do in order to get this running. tyia.
I have created an Azure SQL database with one table.
Table is having data as below
3.Created Console application using C#.
Added Package Microsoft.Data.SqlClient to the Project.
Added following code in Program.cs file,
[Taking reference from here](https://learn.microsoft.com/en-us/azure/azure-sql/database/connect-query-dotnet-visual-studio?view=azuresql), I created a replica of the program.cs file as shown:
using System;
using Microsoft.Data.SqlClient;
using System.Text;
namespace sqltest
{
class Program
{
static void Main(string[] args)
{
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "yourservername.database.windows.net";
builder.UserID = "your_username";
builder.Password = "your_password";
builder.InitialCatalog = "your_database";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
Console.WriteLine("\nQuery data example:");
Console.WriteLine("=========================================\n");
//String sql = "SELECT * FROM dbo.Persons";
String sql = "SELECT LastName, FirstName FROM dbo.Persons";
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
}
}
6.Using above code, I am connecting to Azure SQL and retrieving data from database.
Run the application and getting data from Azure Sql data base as shown below,
Reference links:
https://learn.microsoft.com/en-us/visualstudio/azure/azure-sql-database-add-connected-service?view=vs-2022
I'm having trouble with my code to access a MySQL Database. Everytime I try to open my connection, a System.TypeInitializationException is thrown by MySql.Data.MySqlClient.Replication.ReplicationManager. Here is my code:
DataTable results = new DataTable("Results");
using (MySqlConnection connection = new MySqlConnection("SERVER=127.0.0.1;DATABASE=foo;UID=bar;PASSWORD=foobar;"))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open(); //throws System.TypeInitializationException
command.ExecuteNonQuery();
using (MySqlDataReader reader = command.ExecuteReader())
results.Load(reader);
}
}
Edit: I guess MySQL Driver was corrupt. After an upgrade from Windows 7 to Windows 10 everything worked fine.
I had the same problem but when i installed the MySql.Data.dll using Nuget then the problem is solved
Install MySql.Dll file from Nuget,
not from MySQL Website.
Your connection string format is wrong. Try this :
static string cs = #"server=localhost;user id=bar;password=foobar;database=foo;";
DataTable results = new DataTable("Results");
using (MySqlConnection connection = new MySqlConnection(cs))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open(); //throws System.TypeInitializationException
command.ExecuteNonQuery();
using (MySqlDataReader reader = command.ExecuteReader())
results.Load(reader);
}
}
In my case, it raised error only in production. It was due to a wrong assumption in the MySql.Data package. It for some reason seems to demand to be in the same folder as the orchestrating dll (it was referencing another dll which was referencing MySql). I resolved my issue by removing MySql.Data and instead installing MySqlConnector package as suggested in here.
I need to connect to a Oracle DB (external) through Visual Studio 2010. But I dont want to install Oracle on my machine.
In my project I referenced: System.Data.OracleClient. But its not fulfilling the need.
I have an "Oracle SQL Developer IDE" in which I run SQL queries against oracle db.
I have this code so far:
private static string GetConnectionString()
{
String connString = "host= serverName;database=myDatabase;uid=userName;pwd=passWord";
return connString;
}
private static void ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM myTableName";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
So far I read these blogs:
http://st-curriculum.oracle.com/tutorial/DBXETutorial/index.htm
http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx
So far I have not downloaded anything from Oracle. What steps should I take to make this happen?
First off you need to download and install ODP from this site
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).
Using Nuget
Right click Project, select Manage NuGet packages...
Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess
In code use the following command (Ctrl+. to automatically add the using directive).
Note the different DataSource string which in comparison to Java is
different.
// create connection
OracleConnection con = new OracleConnection();
// create connection string using builder
OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
ocsb.Password = "autumn117";
ocsb.UserID = "john";
ocsb.DataSource = "database.url:port/databasename";
// connect
con.ConnectionString = ocsb.ConnectionString;
con.Open();
Console.WriteLine("Connection established (" + con.ServerVersion + ")");
The next approach work to me with Visual Studio 2013 Update 4
1- From Solution Explorer right click on References then select add references
2- Assemblies > Framework > System.Data.OracleClient > OK
and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE
OracleConnection oraConnection = new OracleConnection(#"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}
and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method
public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;
if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
Install Oracle Client , and add bin location to Path environment varaible of windows
OR
Copy
oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version),
oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll
I want to write a MySql statement that will connect to the database, select a column from the table, then output that data to a text file to a specific location on my computer. I have searched the internet for a couple days now and don't seem to find the answer I am looking for. I am fairly new to c#, MySql, and Visual Studio. I am just trying to learn how to write the correct statements and get the desired result. Any help would be greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Windows.Forms;
using System.IO;
namespace NewPractice
{
public class Connect
{
static void Main()
{
string results = #"server=111.111.11.111; userid=anyone;
password=anypassword; database=anydatabase";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(results);
conn.Open();
//Console.WriteLine(
File.WriteAllLines(
#"C:\Documents and Settings\anyone\My Documents\Tests\testoutput.txt",
results.ToArray());
}
catch (MySqlException ex)
{
Console.WriteLine("Error: (0)", ex.ToString());
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
}
You're writing the contents of the result string to the file, not the data you're attempting to select. You need to run a sql command and get a SqlDataReader object to write your data to the file.
string results = #"server=111.111.11.111; userid=anyone;
password=anypassword; database=anydatabase";
MySqlConnection connection = new MySqlConnection(results);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "select * from mycustomers";
connection.Open();
reader = command.ExecuteReader();
using(var sw = new StreamWriter("C:\MyPath\MyFile.txt"))
{
while (reader.Read())
{
var row = (IDataRecord)reader;
sw.WriteLine(row["myColumn"]);
}
}
connection.Close();
If the database is on your local machine you can use 'select .. into outfile'. http://dev.mysql.com/doc/refman/5.1/en/select-into.html. This will write to a folder on the server so it's not v useful if it's a different machine and you can't copy from there.
There are plenty of tutorials out there for accessing MySQL from .NET.
This is one: http://zetcode.com/db/mysqlcsharptutorial/
In any language, there are a few simple steps to read from a database:
1. connect to the database.
2. execute a query
3. iterate through the results of the query
4. close the connection.
What you are doing in your code is connecting to the database and then trying to write the connection information to a file.
I am trying to connect to Oracle in a 32-bit Console Application. I am getting the following erorr. The code (with the exception of host, username, and password change) is below. It is a simple two function project.
Any help will be appreciated.
I am using C# in Visual Studion 2010 Premium and Oracle 10g. I can connect to the database with Oracle SQL Developer with the information set in the connection string.
---------------ToString--------------------------
--Oracle.DataAccess.Client.OracleException at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure)
at Oracle.DataAccess.Client.OracleException.HandleError(Int32 errCode, Oracle
Connection conn, IntPtr opsErrCtx, Object src)
at Oracle.DataAccess.Client.OracleConnection.Open()
at ConsoleApplication1.Program.GetConnection() in c:\users\maholt\documents\visual studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 61
---------------Message---------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Oracle.DataAccess.Client;
namespace ConsoleApplication1
{
class Program
{
static OracleConnection conn;
static void Main(string[] args)
{
OracleConnection connC = GetConnection();
conn = connC;
simpleQuery();
Console.WriteLine("DONE");
}
public static void simpleQuery()
{
OracleCommand cmd = new OracleCommand("select count(*) as total from console.client");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
try
{
cmd.Connection.Open();
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(Convert.ToString(reader["total"]));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
cmd.Dispose();
}
}
public static OracleConnection GetConnection()
{
Oracle.DataAccess.Client.OracleConnection rtn = null;
try
{
string connstr = "Data Source=//10.10.10.10:1521/PRD2_OLTP;User Id=user; Password=pass;";
rtn = new Oracle.DataAccess.Client.OracleConnection(connstr);
if (rtn.State != System.Data.ConnectionState.Open)
{
rtn.Open();
}
}
catch (Exception ee)
{
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("---------------ToString--------------------------");
Console.WriteLine("--" + ee.ToString());
Console.WriteLine("---------------Message---------------------------");
Console.WriteLine("--" + ee.Message);
Console.WriteLine("-------------------------------------------------");
}
return (rtn);
}
}
}
SQL Developer uses effectively JDBC connection... so it is not really comparable with what happens in .NET :-(
Regarding the Oracle versus .NET version compatibility - I found this rather problematic esp. since the clients don't have always the option to update according to Oracle roadmap...
After researching some I switched to using the Devart components - support everything from Oracle 7.3 up to 11gR2 in .NET 2 up with 32 and 64 bit and come with a "direct-mode option" which means if need be I can run my app without any Oracle client being installed on the machine... not affiliated, just a happy customer...
First - Oracle doesn't support 10g with .net 4.0. You must use 11.2.0.2 or higher to be compliant with Oracle's supported versions.
Second - The problem is you probably don't have ODP.Net installed correctly. This can mean it isn't installed, it was installed to a second instance, or it failed to copy on or more files during installation.
I have some blog posts about these items along with a link to some connection testing applications I wrote. Feel free to use them.
https://tsells.wordpress.com/category/oracle/