Track Database Status Change sql server - c#

I want to Track database status changed in sql server . in my solution ,I have a database that is offline due to restore from primary server .
i want to get hint in my application(C#) when database is offline and when is online. (like sql notification event) .
Thanks .

One way is to check the state of the database using a timer from your application
private void timer1_tick(object sender,EventArgs e)
{
if(CheckDatabaseState() == "ONLINE")
MessageBox.Show("db is online");
else
MessageBox.Show("db is NOT online");
}
Public string CheckDatabaseState()
{
string Constr = #"Data Source=.\SQLEXPRESS;Integrated Security=True;Initial Catalog=master;";
string sql = string.Format("SELECT Name, state_desc FROM sys.databases where name = '{0}'", dbName);
SqlConnection conn;
SqlCommand comm;
SqlDataAdapter adapter;
DataSet ds = new DataSet();
conn = new SqlConnection(Constr);
comm = new SqlCommand(sql, conn);
adapter = new SqlDataAdapter(comm);
adapter.Fill(ds);
return ds.Tables[0]["state_desc"].ToString();
}
Let me know if this helps,

Related

SQL will only search inside of program folder

this same code has worked for several other programs, however i can not get it to function with this program for some reason. what is happening is i select a file location on my desktop to read from, but the program keeps trying to open the file from inside the program files of where i have this program saved.
MessageBox.Show(PATHTEXTBOX.Text);
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath;
string query = "select * from Vendors";
OleDbConnection connect = new OleDbConnection(connString);
OleDbCommand command = new OleDbCommand(query, connect);
connect.Open();
OleDbDataReader reader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable.DefaultView;
connect.Close();
Querying the database using the "SqlDataAdapter" object was successful. I made a case to reproduce your problem and realized the query to the database.
UI page:
Vendors table data:
Test Results:
Code logic:
Query the database by clicking the test button.
Bind the DataGridView control by using code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connStr = #"Data Source=(localdb)\ProjectModels;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//Create an instance of SqlConnection
SqlConnection conn = null;
try
{
conn = new SqlConnection(connStr);
//open database
conn.Open();
string sql = "select * from Vendors";
//Create an object of the SqlDataAdapter class
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
//Create an object of the DataSet class
DataSet ds = new DataSet();
//Use the SqlDataAdapter object sda to fill the new lookup results into the DataSet object ds
sda.Fill(ds);
//Set the DataSource property of the table control
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("An error occurred!" + ex.Message);
}
finally
{
if (conn != null)
{
//Close the database connection
conn.Close();
}
}
}
}
It may be helpful to check your database connection string. Hope that helps you.

error while connecting to mysql in C# asp.net

I have an error while connecting my project into mysql database so i have added the code bellow to my button to fetch all rows and display it in a gridView
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection myconn = new MySqlConnection("server=localhost;uid=root;password=;database=y;");
string strSQL = "select * from welcome";
myconn.Open();
MySqlDataAdapter mydata = new MySqlDataAdapter(strSQL, myconn);
MySqlCommandBuilder cBuilder = new MySqlCommandBuilder(mydata);
System.Data.DataSet ds = new System.Data.DataSet();
mydata.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
myconn.Close();
}
When running the the app it shows an error in myconn.Open();
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: The host localhost does not support SSL connections.
and it pointed to myconn.Open();
change myconn to :
MySqlConnection myconn = new MySqlConnection("server=localhost;uid=root;password=;database=y;sslmode=none");
Make sure that you are adding sslmode=none in myconn
better try with Entity Frame work
Add ADO.NET Entity model,If will ask to connect db and give some name(ex :userentities)
Then, use below code in your coding
userentities context = new userentities();
protected void Button1_Click(object sender, EventArgs e)
{
using (var dbTransactionContext = context.Database.BeginTransaction())
{
//then do the operation
}
}
It's really easy
or other wise follow these steps
1. add your connection string in web config
<add name="UserContext" connectionString="server=localhost;User Id=root;password='';database=databasename;convert zero datetime=True" providerName="MySql.Data.MySqlClient" />
Add follow codes in your code
private MySqlConnection con;
con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["UserContext"].ConnectionString;
con.Open();

ASP.Net can connect to MySQL server, but i cant pull back data?

I am using ASP.NET C# to try and connect to a MySQL server to pull back data into a Gridview. I can connect, but I can't pull back any data. It simply isn't there. There is data on the SQL server of course, but I just can't seem to get in back into my site. Any ideas?
Code for ref:
protected void Page_Load(object sender, EventArgs e){
MySqlConnection conn = new MySqlConnection();
MySqlCommand comm = new MySqlCommand();
MySqlDataAdapter adpater = new MySqlDataAdapter();
DataTable data = new DataTable();
string query;
string connString = "Server=Server address; Database=sql8118918; Uid=my username; Pwd=my password; ";
conn = new MySqlConnection();
conn.ConnectionString = connString;
try
{
conn.Open();
adpater = new MySqlDataAdapter();
comm = new MySqlCommand();
data = new DataTable();
query = "SELECT * FROM products";
comm.Connection = conn;
comm.CommandText = query;
adpater.SelectCommand = comm;
adpater.Fill(data);
GridView1.DataSource = data;
logLabel.Text = ("Connection Successful !");
}
catch(Exception ex)
{
logLabel.Text = ex.ToString();
}
Like I said I can connect but no data is pulled back.
I have also tried to put the data into a string, and then display that string on the front end but all I get is this in the string ?
System.Data.DataRowCollection
What am I doing wrong here?
You should call DataBind() method after set the DataSource property. Take a look here.
GridView1.DataSource = data;
GridView1.DataBind();

Connecting C# to a remote MySQL database

I am trying to connect a C# application to my MySQL database located in a remote server. When I try to execute this simple program, I get the following error: sqlException was unhandled
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("user id=student_abdo;password=XXXXXX;server=178.239.167.XXX;Trusted_Connection=yes;database=student_sms;connection timeout=30");
SqlCommand com = new SqlCommand("UPDATE `sms` SET `id`=23 WHERE `sms`='hi'",con);
com.CommandType = CommandType.Text;
con.Open();
com.ExecuteNonQuery();
con.Close();
}
The SqlClient namespace is for connecting to Microsoft SqlServer databases. If you want to work with MySql, you'll need to find an ADO.NET implementation (3rd party) or determine if there is a way to make it work with OleDb/Odbc.
UPDATE
Apparently, MySql provides its own ADO.NET driver for getting the job done.
As Brian pointed out, you are using the wrong provider. Also, your connection string is wrong. It should read
"Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
You can reference this site for all of the different connection string types for mysql
Here is what you need to download
Keep in mind that Classes for working with MySql in .NET are mostley the same as working with MSSQL with exception that they have My... prefix
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("userid=student_abdo;password=XXXXXX;server=178.239.167.XXX;Trusted_Connection=yes;database=student_sms;connection timeout=30");
MySqlCommand com = new MySqlCommand("UPDATE `sms` SET `id`=23 WHERE `sms`='hi'",con);
com.CommandType = CommandType.Text;
con.Open();
com.ExecuteNonQuery();
con.Close();
}
first of all, you know what is forms of connect string and then established the connection with the database.
bb rec
private void btnretrive_Click(object sender, EventArgs e)
{
string cs = "server=localhost;user id=root;database=world;";
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd = new SqlCommand("select * from world;",conn);
SqlDataReader reader = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
dataGridView1.DataSource = table;
conn.Close();
}

Sql statement works in Access but not when I run from C#

The statement:
SELECT [ToWhom] FROM [myChecks] WHERE [ToWhom] like '*e*'
works fine in Access but when I run it from C# I get back and empty Dataset.
Here is the code:
string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Checkbook.accdb";
OleDbConnection Conn = new OleDbConnection();
Conn.ConnectionString = connectionstring;
OleDbCommand myCommand = Conn.CreateCommand();
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter();
DataSet myDataset = new DataSet();
DataTable EmptyDataTable = new DataTable();
myCommand.CommandText = SQL;
myDataAdapter.SelectCommand = myCommand;
Conn.Open();
try
{
//This part does not throw an error it just return an empty Dataset
myDataAdapter.Fill(myDataset);
Conn.Close();
return myDataset.Tables[0];
}
catch(SyntaxErrorException e)
{
MessageBox.Show(e.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Conn.Close();
return EmptyDataTable;
}
Any help would be appreciated.
In C# with the above connection, use percent (%) as the wildcard, not asterisk (*)
SELECT [ToWhom] FROM [myChecks] WHERE [ToWhom] like '%e%'
Inside MS Access, in the query design window when ANSI 92 option is not set (that is, the usual set-up), the wildcard is asterisk (*), outside of Access is usually percent (%).

Categories

Resources