C# MySQL retrieving a value from a column matching another - c#

So I have a table with the following columns:
ID, name, adress, etc..
I have been doing some research but I cannot come across the right keywords to find out to do what I want. I would like to be able to take the name value (Which would be say... "John Doe" which is in the database already for sure..) and retrieve the ID of it (from the int MySQL value ID).
I have come across the following code but I cannot seem to figure out how to extend its limits to match my needs.
connection2.Open();
cmd.ExecuteNonQuery();
try
{
MySqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(myReader.GetOrdinal("id")));
}
myReader.Close();
}
finally
{
connection2.Close();
}
This is also what I have come up with to the best of my abilities.
MySqlConnection connection2 = new MySqlConnection("Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";");
string query = #"SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";
MySqlCommand cmd = new MySqlCommand(query, connection2);

You should replace the hard coded parameters with sql parameters, but here is a general idea of what you'll need to do here. Using your present sql query.
MySqlConnection sqlConn = new MySqlConnection();
MySqlCommand sqlCmd = new MySqlCommand();
string sSql = "SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";
sqlConn.ConnectionString = "Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";";
sqlCmd.CommandText = sSql;
sqlCmd.CommandType = CommandType.Text;
sqlConn.Open();
sqlCmd.Connection = sqlConn;
MySqlDataReader reader = sqlCmd.ExecuteReader();
List<string> results = new List<string>();
while (reader.Read())
{
results.Add((reader["id"].ToString());
}
reader.Close();
sqlConn.Close();
Keep in mind you can add the reader results to a string, to a list like above, whatever you want to do with it.

this how id en name pawe
clsMySQL.sql_con.Open();
string id = ID;
sql = "SELECT *FROM test";
cmd = new MySqlCommand(sql, clsMySQL.sql_con);
sql_cmd = new MySqlCommand(sql, clsMySQL.sql_con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr["id"].ToString();
user = dr["user_name"].ToString();
pass = dr["password"].ToString();
if (name.Text == user && passw.Text == pass)
{
string depart = id;
Hide();
MessageBox.Show("it works");
// Then show the main form
cracker form = new cracker(name.Text);
form.sid = depart;
form.Show();
MessageBox.Show(ID);
}
}
else
{
MessageBox.Show("Invalid Login please check username and password");
}
clsMySQL.sql_con.Close();
}

Related

upload excel file and update the same records asp.net

I am working on a project where I have to upload the excel file in the SQL server database, and also update if the records already exist so far I have implemented the code using SQL bulk cop which is inserting the excel file to the DB table, but I am stuck how to update if the records already available.
I am using asp.net c# for this, this is my code so far, help me and also guide me the best approach of uploading the excel file to the database
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
int id;
string contactPerson;
string designation;
string company;
string contact;
string emailaddress;
string city;
string region;
string industry;
string division;
string mobile;
string address;
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/uploadExcel/") + FileUpload1.FileName);
String ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
// OleDbConnection myconn =
//new OleDbConnection( #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';");
mycon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr[0].ToString() != "")
{
// Response.Write("<br/>"+dr[0].ToString());
id = Convert.ToInt32(dr[0].ToString());
contactPerson = dr[1].ToString();
designation = dr[2].ToString();
company = dr[3].ToString();
emailaddress = dr[4].ToString();
contact = dr[5].ToString();
mobile = dr[6].ToString();
address = dr[7].ToString();
city = dr[8].ToString();
region = dr[9].ToString();
industry = dr[10].ToString();
division = dr[11].ToString();
UpdateDatabase(id, contactPerson, designation, company, emailaddress, contact,
mobile, address,city,region,industry,division);
}
else
{
break;
}
}
lblmessage.Text = "Data Has Been Updated Successfully";
mycon.Close();
File.Delete(ExcelPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//designation, company, emailaddress, contact, mobile, address,city,region,industry,division
private void UpdateDatabase(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address,String city,String region,String industry,
String division)
{
String query = "insert into Tbl_TempExcelData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
//String mycon = "Data Source=Ali-PC\\SQLEXPRESS; Initial Catalog=ExcelDatabase; Integrated Security=True";
String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
Create user-defined type in sql server with all the valves you want to insert
After that user Sql server merge statement to insert and update record in one query.
How to use Sql Merge
in Sql Merge statment use your user defined table variable as source table and the table in which you want to insert use that as target table.

C# MySQL Query is not working

Error message is,
Connection must be valid and open.
Is this code wrong? How can i solve the problem?
string strConn = "server = localhost; user = root; database = ****; port = 3306; password = ****; Charset = utf8";
using (MySqlConnection conn = new MySqlConnection(strConn))
{
MySqlCommand insertCommand = new MySqlCommand();
conn.Open();
for (int i = 0; i < 10; i++)
{
insertCommand.CommandText = "INSERT INTO master (col_name, col_code)" +
" SELECT * from (select '" + _name[i] + "', '" + _code[i] + "') as tmp" +
" WHERE NOT EXISTS (" +
" SELECT col_code FROM master WHERE col_code = '" + _name[i] + "') limit 1;";
insertCommand.ExecuteNonQuery();
}
conn.Close();
}
Before your for loop need to set connection for your CommandObject like:
InsertCommand.Connection = conn;
You need to assign the connection to your command by using the connection object you created conn.
MySqlCommand insertCommand = conn.CreateCommand();
So, your code goes like this:
string strConn = "server = localhost; user = root; database = ****; port = 3306; password = ****; Charset = utf8";
using (MySqlConnection conn = new MySqlConnection(strConn))
{
MySqlCommand insertCommand = conn.CreateCommand();
conn.Open();
for (int i = 0; i < 10; i++)
{
insertCommand.CommandText = "INSERT INTO master (col_name, col_code)" +
" SELECT * from (select '" + _name[i] + "', '" + _code[i] + "') as tmp" +
" WHERE NOT EXISTS (" +
" SELECT col_code FROM master WHERE col_code = '" + _name[i] + "') limit 1;";
insertCommand.ExecuteNonQuery();
}
conn.Close(); //you don't need this.
}
No need to close the connection by conn.Close(); because the connection gets automatically closed when the using block is exited.
using (MySqlConnection conn = new MySqlConnection(strConn))
{
//your code
}

How to save data to xampp phpmyadmin mysql database from windows form application c#

How to save data to xampp phpmyadmin mysql database from windows form application c# ? variables with data are country1,city1,temperature1.
Database is weather and table is forecast
try
{
string MyConnection2 = "datasource=localhost;port=3307;username=db1;password=db12121";
string Query = "insert into weather.forecast(country, city, temperature) values('" + country1 + "','" + city1 + "','" + temperature "');";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
This could work for you:
MySql.Data.MySqlClient.MySqlConnection connection;
string server = "localhost";
string database = "weather";
string uid = "db1";
string password = "db12121";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand("insert into forecast (country,city,temperature) values(#Country,#City,#Temperature)", connection);
cmd.Parameters.AddWithValue("#Country", country1);
cmd.Parameters.AddWithValue("#City", city1);
cmd.Parameters.AddWithValue("#Temperature", temperature);
cmd.ExecuteNonQuery();
}
else
{
DisplayMessage.Text = "Database connection failed.";
}
}
catch (Exception ex)
{
}
connection.Close();
}

mysql command executescalar returns null in C#

Let's say I have a query result that looks as follows:
ID NAME Phone
---- ---- -----
1 John 123456
2 John 125678
3 John 345678
4 Abby 456789
5 Abby 567890
I want to return just a single row instance of name: John, where the phone number like '12%'.
In c#, I wrote this syntax to get the PersonName variable as the result of the query.
MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
connection.Close();
I don't know whats wrong with my code but the PersonName returns null. What did I do wrong?
We have to be missing something else here. Try the following code sample based on what you provided:
try {
MySqlConnection connection = new MySqlConnection("SERVER=localhost;DATABASE=testdb;UID=root;PASSWORD=;");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
finally {
connection.Close();
}
I have a feeling that for some reason the call to .Open() is failing and the error is being swallowed elsewhere. Try the above and let me know what you find out.
do this : change this (string)command.ExecuteScalar(); by Convert.ToString(command.ExecuteScalar());
MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand command = new MySqlCommand();
connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = Convert.ToString(command.ExecuteScalar());
connection.Close();

Get textbox to show records of the same row of MySQL

I have the following code that when I fill in a name or whatever it may be, it will search through the MySQL DB and show me every name that has what you entered in it.
MySqlConnection connection2 = new MySqlConnection("Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";");
connection2.Open();
string query = #"SELECT DISTINCT name2 FROM childDatabase WHERE name2 Like '%" + childSearch.Text + "%'";
MySqlCommand cmd = new MySqlCommand(query, connection2);
cmd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter(query, connection2);
DataTable dt = new DataTable();
da.Fill(dt);
childSearchCombo.DataSource = dt;
childSearchCombo.ValueMember = dt.Columns[0].ColumnName;
connection2.Close();
Now, this code is fine and it is used for my comboBox. The thing I need is that when you press the button (lets say... btnShow) it is supposed to display the rest of the retrieved from the db in the same row. Right now it currently just displays the index at [0] which is obviously not dynamic for each record and is the obvious flaw in the code that even I understand.
This is the code for it:
MySqlConnection connection2 = new MySqlConnection("Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";");
connection2.Open();
string query = #"SELECT DISTINCT name2, age, gender FROM childDatabase";
MySqlCommand cmd = new MySqlCommand(query, connection2);
cmd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter(query, connection2);
DataTable dt = new DataTable();
da.Fill(dt);
firstNameDisp.Text = dt.Columns[0].ColumnName;
ageDisp.Text = dt.Columns[1].ColumnName;
genderDisp.Text = dt.Columns[2].ColumnName;
So basically the last 3 lines of that code should display the name, age, and gender in the same row as selected in the comboBox.
I have searched for a long time and my knowledge just doesn't seem to be up to par yet. Any help is appreciated!
You should use a using statement to properly dispose your MySQL objects.
This is a code snippet to get you started.
DataTable dt = new DataTable();
string _CS = "Server=" + server + ";Port=" + port + ";Database=" + database + ";Uid=" + uid + ";Password=" + password;
using (MySqlConnection connection2 = new MySqlConnection(_CS))
{
connection2.Open();
string query = #"SELECT DISTINCT * FROM childDatabase";
using (MySqlCommand cmd = new MySqlCommand(query, connection2))
{
// cmd.ExecuteNonQuery(); There's no need to execute this. da.Fill() will
// execute your command.
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
da.Fill(dt);
}
// connection2.Close(); No need to close either. The using statement does that.
}
foreach (var st in dt.AsEnumerable())
{
if (st.Field<string>("name2").Contains(childSearch.Text))
// or .Contains(yourComboBox.SelectedItem.ToString())
{
childSearchCombo.Items.Add(st.Field<string>("name2"));
firstNameDisp.Text = st.Field<string>("your column name");
ageDisp.Text = st.Field<string>(0); // or by index
genderDisp.Text = st.Field<string>("column name or index");
// Note that st.Field<T> also can be a decimal, a bool, an int etc..
}
}
This way you don't need to query for every little bit. I'm also not 100% sure this will entirely work, i think you'll have to bug around a bit.
Anyway, probably there are many better ways to perform this. But i think it's a good learning curve. Good luck!

Categories

Resources