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
Related
The program I have been creating takes a SQL query as a string parameter and passes it to a method where it is then executed. I am able to open my mysql connection for each query, but for some reason I am unable to run any select statements (I have tried both ExecuteReader and ExecuteScalar).
However, when I run an ExecuteNonQuery, it runs it fine. I am able to verify the insert statement worked from the ExecuteNonQuery.
I currently have the same database up in a SQLyog, using the exact same connection information. While the select statement is running, I am simultaneously running "SHOW FULL PROCESSLIST" and I do not see the query being run. Here is the code I have:
private void buttonConnect_Click(object sender, EventArgs e)
{
string tmp = mysqlSelectScalar("select NAME from PRESIDENTS where name like '%trump%';");
string tmp = mysqlSelectScalar("select COUNT(*) from project.PRESIDENTS;");
mysqlnonQuery("insert into PRESIDENTS (ID,NAME) VALUES ('66','TEST');");
}
public string mysqlSelectScalar(string query)
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection cnn = new MySqlConnection(connString);
string result = "";
try
{
MessageBox.Show(query);
MySqlCommand cmd = new MySqlCommand(query, cnn);
using (cnn)
{
cnn.Open();
cmd.CommandTimeout = 10;
result = Convert.ToString(cmd.ExecuteScalar());
}
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("COULD NOT CONNECT TO DATABASE: " + ex.ToString());
}
return result;
}
public void mysqlnonQuery(string query)
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection cnn = new MySqlConnection(connString);
string result = "";
try
{
MessageBox.Show(query);
MySqlCommand cmd = new MySqlCommand(query, cnn);
using (cnn)
{
cnn.Open();
cmd.ExecuteNonQuery();
}
cnn.Close();
connStatus = 0;
}
catch (Exception ex)
{
MessageBox.Show("COULD NOT CONNECT TO DATABASE: " + ex.ToString());
connStatus = 1;
}
}
private void outputTable(string query)
{
try
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter adpt = new MySqlDataAdapter();
conn.Open();
cmd.CommandTimeout = 5;
MySqlDataAdapter sqladapter = new MySqlDataAdapter(query, conn);
DataSet DS = new DataSet();
sqladapter.Fill(DS);
//the above command is what times out. Everything before runs fine
dataGridViewOutput.DataSource = DS.Tables[0];
MessageBox.Show("dataGridViewOutput.DataSource = DS.Tables[0];");
conn.Clone();
}
catch (Exception ex)
{
richTextBoxOutput.Text = ex.ToString();
}
}
The error message I am getting is from a timeout:
System.TimeoutException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I am sure that the connection string is working because I am able to run the mysqlnonQuery method, and when I put print statements in the mysqlSelectScalar method I saw I was able to get past the opening of the connection.
I should also specify that the table I am selecting from is only 45 records, and I am able to run the same select queries from the mysql command line, which complete in about 0.01 seconds.
This code is also being re-purposed from an older project I was working on, with the exact same mysqlSelectScalar method, and was working perfectly.
Any kind of help would be much appreciated.
using System;
using MySql.Data.MySqlClient;
namespace RetrieveCars
{
class Program
{
static void Main(string[] args)
{
string cs = #"server=localhost;userid=dbuser;password=s$cret;database=testdb";
using var con = new MySqlConnection(cs);
con.Open();
string sql = "SELECT * FROM cars";
using var cmd = new MySqlCommand(sql, con);
using MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine("{0} {1} {2}", rdr.GetInt32(0), rdr.GetString(1),
rdr.GetInt32(2));
}
}
}
}
I hope this isn't a repost but I couldn't find an answer yet.
How can I connect to a LibreOfficeBase-database in C#? I don't have MS Access, that's why I only have Libre. So far, this is what I wrote:
private void add_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader reader;
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Users\\user\\Desktop\\data.odb;";
cmd.Connection = con;
cmd.CommandText = "INSERT INTO data(name, age)" +
"VALUES('" + FamilyName.Text + "', '" + Age.Text +"')";
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Close();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
My database is called data.odb and of course it isn't working, because this method is for .accdb files. What do I do for .odb files?
odb is openoffice database. There is a MySQL connector present for working with odb file see here https://wiki.openoffice.org/wiki/Database/Drivers/MySQL_Native/1.0.
Also you might want to go through OpenOffice documentation https://wiki.openoffice.org/wiki/Database#Developer which says how to connect to MS Access https://wiki.openoffice.org/wiki/Connecting_to_Microsoft_Access
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string q2 = "insert into gym.dbo.customer (name, weight, height, add_class, gender, fees) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";
SqlConnection con = new SqlConnection(ss);
SqlCommand cmd = new SqlCommand(q2, con);
SqlDataReader read;
try
{
con.Open();
read = cmd.ExecuteReader();
MessageBox.Show("Welcome to our gym");
while (read.Read()) { };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can I insert and save data into the database using Visual Studio and C#?
This code throws an error. Anyone please give the suggestion to me to solve the error.
image description
At first make sure your the data type of different column of customer table.
Then make sure what type of data you have to save for combobox.
you have to get the selected value from your Combobox. combobox1,combobox2,combobox3 retuns only the class name
System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
You can follow this example
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
The comments are getting a bit busy, so this is the sort of thing you need to do (including parameterising the query):
Specifically, you don't need a reader for an insert statement as it doesn't return a result set.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var sql = "insert into dbo.customer ...";
using (var con = new SqlConnection(ss))
{
var cmd = new SqlCommand(sql , con);
con.Open();
cmd.ExecuteScalar();
MessageBox.Show("Welcome to our gym");
}
}
Hi check that customer table is available in gym Database.
else try this link
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into customer (name,weight,height,add_class,gender,fees) values(#name,#weight,#height,#add_class,#gender,#fees)", con);
cmd.Parameters.AddWithValue("name", this.textBox1.Text);
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I found that your connection string declaration is wrong
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
need to update like below
public string ss = "Data Source=abc\\SQLEXPRESS;Initial Catalog=gym; user id=sa; Password=123456";
Data source will be not be D, It should be Server name.
enter image description here
this code is for the combo box where i want to select some index to show it to my textboxes.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//My program is completely running but not in this section. :(
Is you made an connection between your application and database source using conn object ? You might be used conn object as a connection object but before this was you initialized you Connection ?
Simpy use like
"SqlConnection conn=new SqlConnection("Connection_Source");"
here is your error.
You have to define the connection string for the connection, here i suggest you one best method for executing command.
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
If its just to select value from comboBox and display in textBox , then below code will help you...
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
i'm realising a litel program with windows forms c#, that saves data in ms ACCESS database.
i write this code
OleDbConnection connect = new OleDbConnection();
private void button1_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb";
string fname = textBox1.Text;
string lname = textBox2.Text;
connect.Open();
OleDbCommand cmd = new OleDbCommand(" INSERT INTO user ([nom],[prenom]) VALUES (#fname,#lname)",connect);
if (connect.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("erreur" + ex.Source);
connect.Close();
}
}
else
{
MessageBox.Show("probleme connection");
}
}
and i got this error when executing it
"error in insert methode"
i have not idea the error in insert request. have you an idea
Try this. I added the using-statements and [ ]-brackets to the query string.
string fname = textBox1.Text;
string lname = textBox2.Text;
using(OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb"))
using(OleDbCommand cmd = new OleDbCommand("INSERT INTO [user] ([nom],[prenom]) VALUES (#fname,#lname)", conn))
{
try
{
conn.Open();
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
}
catch (Exception ex) { MessageBox.Show("Erreur" + ex.Source); }
finally { if (conn.State == ConnectionState.Open) { conn.Close(); } }
}
The OLE DB .NET Provider uses positional parameters that are marked with a question mark (?) instead of named parameters.So, Try to use ? instead of named parameter. for example.
INSERT INTO [user] ([nom],[prenom]) VALUES (?,?)
comand.Parameters.Add("nom", OleDbType.VarChar).Value = fname;