connect to mysql using c# - c#

please excuse me for asking a primary question. I need to connect to this link http://sunspares.millenniumit.com/phpmyadmin/ using c#. It is of MySQL and i need to access a table called 'spares' in the 'inventory' database. Can anyone help me to initialize this connection using C#. I found the below coding but i'm confused how to provide the exact server that i need to be connected as well as to the table
con = mysql_connect("localhost","username","password");

Install the mysql connector/net.
Create a new project.
Add reference to: MySql.Data.
Add using MySql.Data.MySqlClient;.
Add the following code to your application:
private void button1_Click(object sender, System.EventArgs e)
{
string MyConString = #"SERVER=localhost;
DATABASE=mydatabase;
UID=testuser;
PASSWORD=testpassword;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from mycustomers";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string thisrow = "";
for (int i= 0;i<Reader.FieldCount;i++)
thisrow+=Reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
}
connection.Close();
}

<connectionStrings>
<add name="MySQLConnectionString" connectionString="server=localhost;User Id=root;pwd=;database=data1;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
-----------------------
using MySql.Data.MySqlClient;
...
MySqlConnection Conn = new MySqlConnection();
Conn = new MySqlConnection(ConnStr);

Related

Unable to insert data into MySQL table via ASP.NET Web Application

I have installed MySQL on my local computer and am trying to enable insertion of data to a created MySQL table from my ASP.NET web application on Visual Studio 2017. I've managed to set up a MySQL connection successfully and created table called 'events'.
Initially, I do not have any syntax or system errors, using the code below, but whenever I try to insert data from my web form upon clicking, no data is inserted into the MySQL table. Any advice if there is anything wrong in my code or any other file configurations?
Later, after I tried installing Connector for .NET, I still cannot insert data into the MySql and I get the below errors in namespace MySqlConnection stating 'the-type-mysqlconnection-exists-in-both-mysql-data-issue' as seen below
Any advice what can be corrected to be able to insert data into my table? Is it in my Insert code or does problem lie elsewhere? Below are my code:
AddEvent.aspx.cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
namespace Prototype3
{
public partial class AddEvent : System.Web.UI.Page
{
//convert event date input into DateTime format on back-end of page
string dateStr = dateinput1.Value;
DateTime date;
//Saving data on added event into MySQL database
string constring = "server=localhost;user id=***********;
password=***********!;
persistsecurityinfo=True;database=homesecretary";
//Connection to database below-check!!
string Query = "INSERT into events (eventTitle) VALUES
('"+tb_eventTitle.Text+"')"; //Parse date input from jQuery
datepicker
MySqlConnection connDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, connDataBase);
MySqlDataReader myReader;
try
{
connDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
connDataBase.Close();
}
Web.config:
<configuration>
<connectionStrings>
<add name="homesecretaryConnectionString"
connectionString="server=localhost;user
id=********; password=********; persistsecurityinfo=True;
database=homesecretary" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
.....
</configuration>
You are doing a very basic/fundamental mistake here.
The MySqlDataReader purpose is to use when we are selecting data. You need to insert data not query so it should be calling ExecuteNonQuery() method:
// for inserts/updates queries
cmdDataBase.ExecuteNonQuery()
Please refer to the following docs for seeing an example on how to insert data in ADO.NET:
MSDN - Insert New Records in to Database
Note: Please don't do string concatenation for creating queries as it is not a good practice instead of that you should be using Parameterized queries. See an example here
To update/insert the data you may need to use ExecuteNonQuery and to fill the DataSet you may use MySqlDataAdapter as follow:
private static string _DBConnectionString = string.Empty;
public static int SetData(string sqlQuery)
{
int iReturn = -1;
try
{
MySqlCommand cmd = new MySqlCommand(sqlQuery);
using (MySqlConnection conn = new MySqlConnection(DBConnectionString))
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
iReturn = cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (Exception E)
{
iReturn = -1;
}
return iReturn;
}
public static object GetData(string sqlQuery)
{
DataSet dtSet = new DataSet();
try
{
MySqlCommand cmd = new MySqlCommand(sqlQuery);
MySqlDataAdapter adpt = new MySqlDataAdapter();
using (MySqlConnection conn = new MySqlConnection(DBConnectionString))
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.CommandTimeout = 0;
adpt.SelectCommand = cmd;
cmd.Connection = conn;
adpt.Fill(dtSet);
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (Exception E)
{
}
return dtSet;
}

Getting the error already an open DataReader associated with this Command which must be closed first

I know It's a repeated question but I tried to add MARS MultipleActiveResultSets=True; in my connection string and it didn't work and still getting the same issue. I'm using SQL Server Management Studio v17.5.
Here's my connection string.
<connectionStrings>
<add name="DefaultConnection"
connectionString="Server=myserver;Database=mydb;User ID=myuser;Password=mypassword;MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
What could be the issue which preventing MARS from getting activated?
public SqlListener()
{
ConnectionString = "DefaultConnection";
connString = ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString;
sqlCmd = new SqlCommand();
sqlConn = new SqlConnection(connString);
sqlCmd.Connection = sqlConn;
sqlCmd.Connection.Open();
SqlDependency.Start(connString);
}
public void executeSQLCMD(string queryType, string queryTxt)
{
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = queryTxt;
SqlDataReader reader = sqlCmd.ExecuteReader();
}
and then another switch with multiple data readers
switch (queryType)
{
case "SelectAHTQ":
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "SP_1";
// fails here--> SqlDataReader AHTReader = sqlCmd.ExecuteReader();
while (AHTReader.Read())
{
LiveAHTDetails details = new LiveAHTDetails();
details.AHT = AHTReader.GetDouble(0);
details.ccName = AHTReader.GetString(1);
details.connectionID = connectionId;
this.liveStatus.liveDetails.Add(details);
}
break;
.....
Thanks
You must close the DataReader object before executing another SQL statement.

SQL parameters not working

This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:
private void btnAdd_Click(object sender, EventArgs e)
{
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
string query =
"INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (#barcodeValue, #nameValue, #dateValue, #quantityValue, #priceValue) ;";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
using (var cmd = new SqlCommand(query, conDataBase))
{
cmd.Parameters.AddWithValue("#barcodeValue", tbxBar.Text);
cmd.Parameters.AddWithValue("#nameValue", tbxName.Text);
cmd.Parameters.AddWithValue("#dateValue", dateDate.Value.Date);
cmd.Parameters.AddWithValue("#quantityeValue", tbxQua.Text);
cmd.Parameters.AddWithValue("#priceValue", tbxPrice.Text);
}
conDataBase.Close();
}
The code might just be wrongly build or I could be missing some part I'm not sure.
I figured out what was not working, was the connection string. So opening a new question for that.
What i had to do is to open the connection and then execute the command
You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:
using (var cmd = new SqlCommand(query, conDataBase))
{
// set parameters...
cmd.ExecuteNonQuery();
}

How to connect to a mysql database in C# and mimic the SELECT, UPDATE and INSERT functions

How can I connect to a MySQL database in C#, and use it to UPDATE values in the database, INSERT values in the database and SELECT values from the database.
Also, is it possible to get the value of the row, and mimic this PHP in C#?
$query = mysql_query("SELECT * FROM foo WHERE foo = 'foo');
while($row = mysql_fetch_assoc($query)) {
$foo1 = $row['foo1'];
//and so on
}
You have to download the MySql Connector/.NET.
How to connect to MySQL 5.0 using c# and mysql connector/net! lists some sample code which is quite similar to what you have:
private void button1_Click(object sender, System.EventArgs e)
{
string MyConString = "SERVER=localhost;" +
"DATABASE=mydatabase;" +
"UID=testuser;" +
"PASSWORD=testpassword;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from mycustomers";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string thisrow = "";
for (int i= 0;i<Reader.FieldCount;i++)
thisrow+=Reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
}
connection.Close();
}
First of all you have to learn about ADO.NET provider classes - They are responsible to establish a database session, execute commands (queries) and retrieve the results) and after that you have to download the MySql Connector API (Data Provider API) and learn the Provider class of mysql connector.
Connector/NET Examples
1- add References to my project : MySql.Data.MySqlClient
2- install the MySQL for Visual Studio download link :
https://dev.mysql.com/downloads/windows/visualstudio/
note: to create database Mysql free go to the link:
https://www.freesqldatabase.com/
the code :
string stconnetionString = "Server=Server name; Port=port number;
Database= DB name; Uid=User namw; Pwd=password;";
MySqlConnection conn = new MySqlConnection(stconnetionString);
try
{
conn.Open();
MySqlCommand mycmd = conn.CreateCommand();
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = "insert into Student(columes name) values(.....)";
mycmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Saved", "Window Application ", MessageBoxButtons.OK, MessageBoxIcon.Information);
clear();
}
catch (Exception)
{
throw;
}

connecting to sql database c# asp.net

hallo there
This is a very basic question. I am currently a student and have done ASP.NET with C#.
For our purposes it was required to do work with an access database where connecting to it and adding data etc.was very easy.
My feeling is that access is not used much in the real world and would just like to enquire on the easiest and most correct way of establishing a connection to Microsoft Sql Server Database(Transact sql).
In my case the database is called dbActivities with primary data file being dbActivitiesData.mdf.
OleDbDataConnection conn;
conn = new OleDbConnection = #"Provider=Microsoft.Jet.Oledb.4.0:"
#"Data Source=DataBase.mdb";
conn.Open();
Regards
My feeling is that access is not used much in the real world
Unfortunately Access is still very much used in the real world :-)
As far as the correct way is concerned I would recommend you wrapping the connection into a using block to ensure proper handling:
class Program
{
static void Main()
{
var connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\work\DataBase.mdb";
using (var conn = new OleDbConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
}
}
And as far as Microsoft SQL Server is concerned:
var connectionString = #"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
string strSQLCommand;
SqlCommand command;
SqlConnection conn = null;
conn =new SqlConnection("Data Source=serverName\IP;Initial Catalog=dbActivities;UID=User;PWD=Password;Max Pool Size=500;");
strSQLCommand = "Your Command";
command = new SqlCommand(strSQLCommand, conn);
command.ExecuteNonQuery();
conn.Close();

Categories