I've always used Oledb Connection.
but now I need to connect with my Database via Sql connection
yet I don't know how to do so,
can some one provide me an example of a database connected with sql connection?
this code needs a sql connection to be done successfully.
protected void Button1_Click(object sender, EventArgs e)
{
string st = this.TextBox1.Text;
string sqlstr2 = "select * from hsinfo WHERE rname='"+st+ "'";
SqlCommand cmd = new SqlCommand(sqlstr2,);
using (SqlDataReader rd = cmd.ExecuteReader())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
You can check the official Microsoft page for more details SqlConnection Class, but I will reproduce the given example below ...
Aditionally you can check also the Connection String Syntax linked in the previous link.
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
This is a simple example code and it's working. This might help you.
Here NextMonth,NextYear,ProcessedDate are auto calculated values comes from another function don't think about that.
String cs = #"Data Source=LENOVO-G510;Initial Catalog=Nelna2;Persist Security Info=True;User ID=sa;Password=123";
protected void Save_Click(object sender, EventArgs e)
{
// SqlConnection con = new SqlConnection(cs);
using (SqlConnection con = new SqlConnection(cs))
{
try
{
SqlCommand command5 = new SqlCommand("insert into MonthEnd (month,year,ProcessedDate) values (#month2,#year2,#ProcessedDate2) ", con);
command5.Parameters.AddWithValue("#month2", NextMonth);
command5.Parameters.AddWithValue("#year2", NextYear);
command5.Parameters.AddWithValue("#ProcessedDate2", ProcessedDate);
command5.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
}
}
Connection string can be found in DB properties. right click on DB -> properties and Get the Connection String
There is no enougth information to build connection for you, but in the shortes you sth like this:
Server=...;Database=...;User ID=...;Password=...;
For more information just check ConnectionStrings website.
try below code and for more information about c# SQL server connection see this SQL Server Connection
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I would do something like this:
public static List<Test> GetTests(string testVariable)
{
DataTable result = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Open();
GetQuery(
connection,
QueryGetTests,
ref result,
new List<SqlParameter>()
{
new SqlParameter("#testVariable", testVariable)
}
);
return result.Rows.OfType<DataRow>().Select(DataRowToTest).ToList();
}
}
private static void GetQuery(SqlConnection connection, string query, ref DataTable dataTable, List<SqlParameter> parameters = null)
{
dataTable = new DataTable();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 120;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
using (SqlDataAdapter reader = new SqlDataAdapter(command))
{
reader.Fill(dataTable);
}
}
}
I think this can help you.
string sqlString = "select * from hsinfo WHERE rname=#st";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.Add("#st", st);
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
}
}
Trick:
Create a file with .udl Extension on your Desktop
Run it by Double click
Compile form by Choosing provider, username, password, etc...
Test connection and save
Close the form
Open now the .udl file with Notepad
You will see the connection string that you can use with ADO.NET
Please I want to know how to retrieve a data on the same row in a MS Access database using Visual C#
I want to get the meaning of a keyword from my database when it is selected from a combo box
Here is my code;
private void cmd_SearchResult_Click(object sender, EventArgs e)
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\hp\Documents\KnowledgeBase.accdb;
Persist Security Info=False;";
using (var conn = new OleDbConnection(connection.ConnectionString))
using (var command = connection.CreateCommand())
{
command.Connection = conn;
command.CommandText = "select Meaning from KnowledgeBase where Keyword = #Keyword";
command.Parameters.AddWithValue("Keyword", String.Copy(cbo_SearchResult.Text));
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
lbl_Display.Text = reader["Meaning"].ToString();
}
}
}
Try something more like the following. I'm not sure what the "connection" object is but lets go with a simple string as shown.
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\hp\Documents\KnowledgeBase.accdb;
Persist Security Info=False;";
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "select Meaning from KnowledgeBase where Keyword = #Keyword";
command.Parameters.AddWithValue("Keyword", cbo_SearchResult.Text);
object result = command.ExecuteScalar();
if (result != null)
{
lbl_Display.Text = result.ToString();
}
}
}
The error message: Access to the path 'C:\backupSALES.sql' is denied.
Here is mycode:
private void BackupSALES()
{
string constring = "server=localhost;user=root;pwd=1234;database=sales;";
string file = "C:\\backupSALES.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ExportToFile(file); //PROMTS AN ERROR
conn.Close();
}
}
}
}
I have been doing backup of MySQL tables using MySqlBackup.dll in C#. I have no idea on how to backup specific table inside a MySQL schema. How can I backup only one or two specific tables using C#?
According to this documentation section, you can specify it in the MySqlBackup.ExportInfo using the List<string> property called TablesToBeExportedList.
So, something like this should work:
string constring = "server=localhost;user=root;pwd=1234;database=test1;";
string file = "Y:\\backup.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ExportInfo.TablesToBeExportedList = new List<string> {
"Table1",
"Table2"
};
mb.ExportToFile(file);
}
}
}
I am working on an C# application which would use the remote MySQL database located in my website hosted on a Linux server with PHP & MySQL support.
I tried to connect directly to the MySQL database using MySql.Data.MySQLClient Reference, as a result, my program is throwing following exception :
"Unable to connect to any of the specified MySQL hosts."
I searched many tutorials but got no solutions... getting the same error.
Can anybody please tell me how to do this.
Please suggest any online links or tutorials or your own idea.
Please help me.
here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace mysq
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string conn = "Server = myserver;database = db ;uid = username ;password = pwd ;";
MySqlConnection con = new MySqlConnection(conn);
con.Open();
if (con.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand("Select * from table", con);
DataTable dt = new DataTable();
MySqlDataAdapter ad = new MySqlDataAdapter(cmd);
ad.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch (Exception)
{
throw;
}
}
}
}
Thanks in advance..
I've written an own class with functions for my mysql-connection.
First of all declare the server connection:
string ServerConnection = "Server=localhost;Port=1234;Database=YourDb;Uid=user;password=pass;"
This is how I select data:
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
using(var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
The call:
List<string> allRows = new List<string>();
DB_Select("SELECT field1 FROM table1 WHERE 1", allRows);
Notice: For every field you are selecting, you have to pass an own list which will be filled with the output.
For updating your database it would be quite the same function. You just wouldnt have to grad the output. Could look like this:
public static void DB_Update(string s)
{
try
{
using (var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
int numRowsUpdated = cmd.ExecuteNonQuery();
if(numRowsUpdated < 0)
{
MessageBox.Show("Warning DB-Contact: Affected_rows < 0!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Updating database failed!\n\nSQL: {0}\n\nERROR: {1}",s,ex.Message));
}
}
You have to provide proper connection string in your program, i am suspecious you are passing proper IP address or hostname of the server where you hosted the database. As a first step try to ping the db server to make sure it is reachable from your machine. If it is reachable try as follows:
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
string conn = "Server =<provide proper ip address >;database = db ;uid = username ;password = pwd ;";
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
More details here : http://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html