How can I point my ASP.NET MVC application to a MySQL database?
Once you download the MySQL ADO.NET Connector it's a simple matter of referencing the assembly in your project and writing the queries, the same way you would do in any other application, nothing specific MVC:
using (var connection = new MySqlConnection(ConnectionString))
using (var cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT name FROM foo;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("name"));
// TODO: do something with the name ...
}
}
}
Related
I'm Using .NET Core 2.1.2.
I use SQL Database for DB and run the following code, the second sqlbulk.WriteToServer raises "Unexpected existing transaction" exception.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
namespace sqldb
{
class Program
{
static void Main(string[] args)
{
var constr = new SqlConnectionStringBuilder(){
DataSource = "xxxxxxxx.database.windows.net",
UserID = "xxxxxxx",
Password = "xxxxxx"
};
using (var scope = new TransactionScope()){
constr.InitialCatalog = "DB1";
var dtable = new System.Data.DataTable();
dtable.TableName = "T1";
dtable.Columns.Add("C1");
var drow = dtable.NewRow();
drow["C1"] = 1;
dtable.Rows.Add(drow);
using (var con = new SqlConnection(constr.ToString())){
con.Open();
var sqlbulk = new System.Data.SqlClient.SqlBulkCopy(con);
sqlbulk.DestinationTableName = "T1";
sqlbulk.WriteToServer(dtable);
}
constr.InitialCatalog = "DB2";
using (var con = new SqlConnection(constr.ToString())){
con.Open();
var sqlbulk = new System.Data.SqlClient.SqlBulkCopy(con);
sqlbulk.DestinationTableName = "T1";
sqlbulk.WriteToServer(dtable);
}
scope.Complete();
}
}
}
}
I executed the following query on each DB and confirmed the status of Elastic Transaction, it was registered as DTC.
SELECT * FROM sys.dm_tran_active_transactions
In Transaction Scope, inserting data with sqlbulkcopy to multiple DBs of SQL Database seems to cause an error, but is there some workaround?
(In the Transaction Scope, inserting data with multiple SqlBulkCopy for the same db / simple insert for multiple db is working fine)
Looks like SqlBulkCopy gets confused with System.Transactions. With your SqlConnection already enlisted in the System.Transactions.Transaction, you can start a "nested" transaction with the SqlConnection.BeginTransaction, and pass that transaction to SqlBulkCopy. EG
using (var con = new SqlConnection(constr.ToString()))
{
con.Open();
using (var tran = con.BeginTransaction())
{
var options = new SqlBulkCopyOptions();
var sqlbulk = new SqlBulkCopy(con,options,tran);
sqlbulk.DestinationTableName = "T1";
sqlbulk.WriteToServer(dtable);
tran.Commit();
}
}
Preface: I have already and can connect to the respective databases in Amazon RDS from MySQL Workbench hence rendering my username, instance url, port number as well as password to be correct.
I am creating an online application for ASP.NET and need to connect to Amazon RDS
s MariaDB instead. I tried to do it via web.config or c# code way but both doesn't work. Advice needed.
Method 1
Web.config:
<add name="rdbs" connectionString="Server=xxxxxx.xxxxxx.ap-southeast-1.rds.amazonaws.com:3306; Database=xxx; Uid=xxxx; Pwd=xxxx;" providerName="MySql.Data.MySqlClient"/>
For my C# code side:
string connStr = ConfigurationManager.ConnectionStrings["rdbs"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connStr))
Method 2
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Initial Catalog"] = "xxxx";
builder["Data Source"] = "xxxxx.xxxx.ap-southeast-1.rds.amazonaws.com";
builder["integrated Security"] = true;
builder["Uid"] = "xxxx";
builder["Pwd"] = "xxxx";
string connexionString = builder.ConnectionString;
SqlConnection connexion = new SqlConnection(connexionString);
try { connexion.Open(); return true; }
catch { return false; }
This is the form of errors I am facing:
Message "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)"
Thanks!
This actually solved it.
Grab MySql.Data.Entity from Nuget
Have this in web.config
<add name="connRDB" connectionString="Data Source=xxxxx.xxxx.ap-southeast-1.rds.amazonaws.com;port=3306;Initial Catalog=xxxxx;User Id=xxxxx;password=xxxx" providerName="MySql.Data.MySqlClient" />
On the code side
string constr = ConfigurationManager.ConnectionStrings["connRDB"].ConnectionString;
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("Select * FROM orders"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = conn;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
I'm a complete beginner in ASP.Net webservices can anyone point me to a good tutorial by which I may implement a web service with SQL Server database connectivity?
Thanks in advance
1. Create the Project in Visual Studio
go to Visual Studio>New Project(select .Net Framework 3.5) >ASP.net Web Service Application
This will create a web service with a HelloWorld example like
public string HelloWorld()
{
return "Hello World";
}
2. Create a Database and Obtain the connection string
3. Define WebMethod
To create a new method that can be accessed by clients over the network,create functions under [WebMethod] tag.
4.Common structure for using database connection
add using statements like
using System.Data;
using System.Data.SqlClient;
Create an SqlConnection like
SqlConnection con = new SqlConnection(#"<your connection string>");
create your SqlCommand like
SqlCommand cmd = new SqlCommand(#"<Your SQL Query>", con);
open the Connection by calling
con.Open();
Execute the query in a try-catch block like:
try
{
int i=cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception e)
{
con.Close();
return "Failed";
}
Remember ExecuteNonQuery() does not return a cursor it only returns the number of rows affected,
for select operations where it requires a datareader,use an SqlDataReader like
SqlDataReader dr = cmd.ExecuteReader();
and use the reader like
using (dr)
{
while (dr.Read())
{
result = dr[0].ToString();
}
dr.Close();
con.Close();
}
Here is a video that will walk you through how to retrieve data from MS SQL Server in ASP.NET web service.
I have a SQLite database with one table for cities name now I want to include this database to my monotouch project, connect to this database and select to this table. But I can find any tutorial to do this.
I don't new to create the database or create a new record. I just need to read the table.
Can anyone explain me how can I connect to my sqlite database an make a select.
Thanks in advance.
UPDATE
using(var connection = new SqliteConnection ("Data Source=zurfers.sqlite"))
{
using (var cmd = connection.CreateCommand()) {
connection.Open ();
cmd.CommandText = "SELECT * FROM City";
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
wordCollection = (string[])reader ["Name"];
}
}
}
}
include your DB file in your MonoTouch project and mark it as content.
using(var connection = new SqliteConnection ("Data Source=MyDatabase.sqlite"))
{
using (var cmd = connection.CreateCommand()) {
connection.Open ();
cmd.CommandText = "this is my query";
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
code = (string)reader ["ColumnName"];
}
}
}
}
I'm new to windows mobile programming and I'm trying to create a Windows Mobile 6 application using sqlite. Write now I have built a dummy test application where I try to read the contents of a an sqlite table.
The problem is that I keep receiving SQLiteException: Unable to open the database file.
My code is below:
using (var cn = new SQLiteConnection(#"Data Source=C:myfirsttest.s3db;"))
{
try
{
//Connect to SQLite database
cn.Open();
//Create the SQL Command
var cmd = new SQLiteCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM MyTable";
//Retrieve the records using SQLiteDataReader
var dr = cmd.ExecuteReader();
while (dr.Read())
{
//display records
var id = dr["ID"].ToString();
}
}
catch(Exception ex)
{
//display any exeptions
var except = ex.Message;
}
finally
{
cn.Close();
}
}
Can anyone help me please with that? Or suggest a tutorial where I can find how to setup sqlite in a windows mobile 6 project?
Windows CE (the base OS for WinMo) does not have drives nor does it have a concept of a working folder. This means that all paths must be fully qualified. You probably want something like:
new SQLiteConnection(#"Data Source=\myfirsttest.s3db;")
or
new SQLiteConnection(#"Data Source=\[my app path]\myfirsttest.s3db;")