I am trying using c# code to connect to mysql server that installed on vmware machine and execute query and I can`t do that.
I tested the connection with uld file on my host and that worked.
I also tested the code on a sql server that I am not hosting on my pc and that was worked for me.
private void button1_Click(object sender, EventArgs e)
{
connString = "SERVER=(Main Server Ip)\\SSER;PORT=3306;DATABASE=......;UID=.......;PASSWORD=......";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
// MessageBox.Show("connection success");
string query = "SELECT * FROM dbo.Table_1";
//Create Command
MySqlCommand cmd = new MySqlCommand(query, conn);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
Console.WriteLine(dataReader["id"] + "");
Console.WriteLine(dataReader["num"] + "");
}
conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Related
I am developing a desktop application in c# visual studio 2013, where I want to create a feature in which a user is allowed to restore and backup the Database by itself. but problem is that it doesn't backup or restore database after deploy project.
When I try to Backup it says!
Database 'DatabaseName' does not exit.Make sure the name is entered correctly.
BACKUP DATABASE is terminating abnormally.
When I try to Restore Database it says
System.Data.Sqlclient.SqlException (0x80131904): User does not have permission to alter database .mdf', the database does not exit, or the the database in not in a state that allows access checks. and so on!
I am using SQL Server Express 2012 by attaching mdf file to the application, when i try to backup using query it works when i add Connection String through SQL Server but after attach mdf file i won't work .
have watch some tutorial videos and figured out some codes but I got nothing
here is my BACKUP code!
private void buttonbackup_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\neyadatabase.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
String sql = "BACKUP DATABASE neyadatabase TO DISK = '" + backuploca.Text + "\\neyadatabase - " + DateTime.Now.Ticks.ToString() + ".Bak'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show("backup done successfully!");
con.Close();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and here is my RESTORE Code!
private void buttonrestore_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\neyadatabase.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
string sqlStmt2 = string.Format("ALTER DATABASE [neyadatabase.mdf] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE [neyadatabase.mdf] FROM DISK='" + restoreloca.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [neyadatabase.mdf] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successefully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I am a beginner in this if anyone is going to help me please give some example too so that I can better understand!
Thank you
For backup use :
private void buttonbackup_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConn = new SqlConnection())
{
dbConn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=neyadatabase;Integrated Security=True;Connect Timeout=30;";
dbConn.Open();
using (SqlCommand multiuser_rollback_dbcomm = new SqlCommand())
{
multiuser_rollback_dbcomm.Connection = dbConn;
multiuser_rollback_dbcomm.CommandText= #"ALTER DATABASE neyadatabase SET MULTI_USER WITH ROLLBACK IMMEDIATE";
multiuser_rollback_dbcomm.ExecuteNonQuery();
}
dbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = yourConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = new SqlCommand())
{
backupcomm.Connection = backupConn;
backupcomm.CommandText= #"BACKUP DATABASE neyadatabase TO DISK='c:\neyadatabase.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And for restore :
private void buttonrestore_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection restoreConn = new SqlConnection())
{
restoreConn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=neyadatabase;Integrated Security=True;Connect Timeout=30;";
restoreConn.Open();
using (SqlCommand restoredb_executioncomm = new SqlCommand())
{
restoredb_executioncomm.Connection = restoreConn;
restoredb_executioncomm.CommandText = #"RESTORE DATABASE neyadatabase FROM DISK='c:\neyadatabase.bak'";
restoredb_executioncomm.ExecuteNonQuery();
}
restoreConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Backup and restore bak file. Mdf/ldf is for attaching not backup.
I hope this helps you.
If you faced any problem let me know to update my answer ;). Good luck
(C#/ .Net Framework4.0 / VS2017).
made a c# windows form with sqlcon expressconnection database,but rly not sure how to create a setup for other client...
i have made a windows form application with a database with sqlconnection in it. im using advance installer to create a setup so i can put the .mdf and .idf files with prerequsites easily.
added connection string as:
public static class DAL
{
public static DataTable ExecSP(string spName, List<SqlParameter> sqlParams = null)
{
string strConnect = "Server=PC\\SQLEXPRESS;Database=MyLoginApp;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection();
DataTable dt = new DataTable();
try
{
//Connect to the database
conn = new SqlConnection(strConnect);
conn.Open();
//Build an sql command / query
SqlCommand cmd = new SqlCommand(spName, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(sqlParams.ToArray());
//Execute command
SqlCommand command = conn.CreateCommand();
SqlDataReader dr = cmd.ExecuteReader();
//fill datatable with the results
dt.Load(dr);
}
catch (Exception ex)
{
throw ex;
}
finally
{
//No matter what happends this will run
conn.Close();
}
return dt;
}
}
When it trying to execute the following code:
private void btnLogin_Click(object sender, EventArgs e)
{
List<SqlParameter> sqlParams = new List<SqlParameter>();
sqlParams.Add(new SqlParameter("Username", TxtUsername.Text));
sqlParams.Add(new SqlParameter("Password", txtPassword.Text));
DataTable dtLoginResults = DAL.ExecSP("ValidateLogin", sqlParams);
string eUser;
string ePass;
eUser = TxtUsername.Text;
ePass = txtPassword.Text;
if (dtLoginResults.Rows.Count == 1)
{
//We know login is valid
string user = dtLoginResults.Rows[0]["Username"].ToString();
MessageBox.Show(user + " Berhasil Masuk!");
this.Hide();
ListMeja lm = new ListMeja();
lm.ShowDialog();
}
else
{
//invalid login
MessageBox.Show("Password Salah");
}
}
gets an error popup window in other client after run the .exe program
Unhandled exception has occured in your application. if you click Continue, the application will ignore this error and and attempt to continue. A network -related or instance-specific error occured while establish a connection to SQL server.The server 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: 26 - Error Locating Server/Instance Specified).
what im doing wrong here ?
Please try to Connect SQL Server With SSMS from Your system.
After Successfully Login Please Edit your string strConnect = "Server=PC\\SQLEXPRESS;Database=MyLoginApp;Trusted_Connection=True;"; connection string as per SSMS Connected.
well.. this is the solution
SqlConnection con = new SqlConnection(#"Data Source = .\SQLEXPRESS;" +
#"AttachDbFilename=|DataDirectory|\MyLoginApp.mdf;Integrated Security = True;User Instance=True");
private void Form1_Load(object sender, EventArgs e)
I am trying to write a MySQL query in C# as below,I don't see any errors but neither I see the required output, the query works fine in mysqlworkbench ,am using MySql.Data.dll connection 6.9.9,what am I missing?how to debug what is wrong?
string connectionString = "server=10.xx.xxx.xx;database=databasename;uid=username;pwd=password;";
var conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = connectionString;
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "select bb.version,bb.baat,bb.au from build bb where bb.version='x.xxx' and bb.state='COMPLETE'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0] + " -- " + rdr[1]);
Console.ReadLine();
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
try to change:
from rdr[0]
to:
rdr.GetString(0)
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string MyConString = "SERVER=http://10.54.3.208:8080/Ager/person;" + "DATABASE=agero;" + "UID=root;" + "PASSWORD=root;";
MySqlConnection con = new MySqlConnection(MyConString);
//MySqlConnection command = con.CreateCommand();
con.Open();
string s = "select * from boopathi where STU_ID =#sid and STU_PWD =#pwd";
MySqlCommand cmd = new MySqlCommand(s, con);
cmd.Parameters.AddWithValue("#sid", TextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#pwd", TextBox2.Text.ToString());
cmd.ExecuteNonQuery();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
Server.Transfer("WebForm1.aspx");
}
}
//close connection
con.Close();
}
catch (Exception ex)
{
Response.Write("An error occured: " + ex.Message);
}
}
In localhost it is working perfectly. Once I set my remote link instead of localhost. It's not connecting anymore. I am getting exception like Unable to connect to any of the specified MySQL hosts.
Try it:-
MySqlConnection c = new MySqlConnection("server=10.54.3.208; database=agero; uid=root; pwd=root");
OR
string MyConString = "SERVER=10.54.3.208;" + "DATABASE=agero;" + "UID=root;" + "Pwd=root;";
refer this link for more information MySQL Connector
I hope it may help you.
Try this one:
http://www.c-sharpcorner.com/uploadfile/camilord/connecting-to-remote-mysql-linux-server-using-visual-C-Sharp/
I hope this will solve your problem
This is code i wrote to add some text to accordion pane on a button click:
protected void Button1_Click1(object sender, EventArgs e)
{
//Use a string variable to hold the ConnectionString.
string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb";
System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection();
cn.ConnectionString = connectString;
//Create an OleDbConnection object, and then pass in the ConnectionString to the constructor.
//OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString);
try
{
//Open the connection.
cn.Open();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl("Open Error"));
}
string selectString = "SELECT * FROM BasicInfo";
//Create an OleDbCommand object.
//Notice that this line passes in the SQL statement and the OleDbConnection object
OleDbCommand cmd = new OleDbCommand(selectString, cn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
//Note: The OleDbDataReader is forward-only.
try
{
OleDbDataReader reader=null;
try
{
reader = cmd.ExecuteReader();
}
catch (Exception es)
{
AccordionPane1.Controls.Add(new LiteralControl(" datareader"));
}
string s = "s";
reader.Read();
s = reader["S_No"].ToString();
AccordionPane1.Controls.Add(new LiteralControl(s));
//Close the reader and the related connection.
reader.Close();
cn.Close();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl(" Read Error"));
}
}
I have my access 2007 database in the folder i specified in the connectString. When im viewing in the browser, on the button click i am getting all the three exceptions:
What might be the problem in opening the database? Do i need to make any other changes?
Change
Provider=Microsoft.Jet.OLEDB.4.0;
to
Provider=Microsoft.ACE.OLEDB.12.0
Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb
Hopefully it will solve the issue.
you connection string might be cause of isssue
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\abc.mdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
this For access 2007 also check the path of database is cocrect.
You can use |DataDirectory| instead of real path and you have to change the Provider=Microsoft.ACE.OLEDB.12.0 (as suggested by #MMK)
string connectString = #"Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\Students1.accdb;Persist Security Info=False;";
and always use using block which dispose IDisposable objects properly.
using(OleDbConnection cn=new OleDbConnection())
{
using(OleDbCommand cmd=new OleDbCommand())
{
cn.ConnectionString=connectionString;
cmd.CommandText=selectString;
cmd.Connection=cn;
...
}
}