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();
Related
I'm trying to execute multiple updates like this
UPDATE clients SET name = :name WHERE clientId = :clientID
I've tried something like this
OracleConnection con = new OracleConnection(connectionString);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText =
"begin " +
" UPDATE clients SET name = " + name1 + " WHERE clientId = " + clientId1 +
" UPDATE clients SET name = " + name2 + " WHERE clientId = " + clientId2 +
"end;";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
but I need to execute hundreds of parameterized updates like the first one
I am connecting to a compact SQL database server through a WCF service and keep getting the following except on the Command.ExecuteNonQuery(). I have tried fixing this but just don't know what's wrong.
The exception:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred
in System.Data.SqlServerCe.dll but was not handled in user code
The code:
//The connectionString can be found in the properties table of the database
string connString = "Data Source=C:\\Users\\User\\documents\\visual studio 2012\\Projects\\ADO_LINQ\\ADO_LINQ\\App_Data\\MyDatabase.sdf;Persist Security Info = False";
SqlCeConnection myConnection = new SqlCeConnection(connString);
myConnection.Open();
// Create the query
string myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + "," +
firstName + ", " +
lastName + ", " +
phoneNumber + ", " +
address + ", " +
dateOfBirth + ");";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
//Run the command
myCommand.ExecuteNonQuery();
//Close the connection
myConnection.Close();
You are missing Single quotes around your string data types, Assuming only registrationID is Integer data type and all other columns are String data type , your query should look something like ......
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + ", '"+ firstName +"' , '"+lastName+"' , '"+phoneNumber+ "', '"+ address +"', '"+dateOfBirth+"' );";
A better and safer option would be to use Parametrised query. Something like this.....
String connString = #"Data Source=C:\Users\User\documents\visual studio 2012\Projects\ADO_LINQ\ADO_LINQ\App_Data\MyDatabase.sdf;Persist Security Info = False";
using(SqlCeConnection myConnection = new SqlCeConnection(connString))
{
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (#registrationID , #firstName , #lastName , #phoneNumber, #address , #dateOfBirth );";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
// Add parameters
myCommand.Parameters.AddWithValue("#registrationID" ,registrationID);
myCommand.Parameters.AddWithValue("#firstName" , firstName);
myCommand.Parameters.AddWithValue("#lastName" , lastName);
myCommand.Parameters.AddWithValue("#phoneNumber" , phoneNumber);
myCommand.Parameters.AddWithValue("#address" , address);
myCommand.Parameters.AddWithValue("#dateOfBirth" , dateOfBirth);
//Open Connection
myConnection.Open();
//Run the command
myCommand.ExecuteNonQuery();
}
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();
}
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!
first time I'm doing an insert from ASP.NET/C# and I'm having a little issue. I keep getting the following error every time this code runs: " ExecuteNonQuery: CommandText property has not been initialized" Does anyone know what this means and how I fix it?
Thanks in advance!
string sqlQuery = "INSERT INTO ATI_LOG_IO (Date, Connect_Time, Disconnect_Time, ATI_Rep, Reason_For_Access, Property_Contact, Case_Number, Comments, Property_ID)";
sqlQuery += "VALUES (#Today, #Connect, #Disconnect, #Rep, #Reason, #Contact, #CaseNum, #Comments, #PropertyID)";
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = dataConnection.CreateCommand())
{
dataConnection.Open();
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.Add("#Today", DateTime.Today.ToString());
dataCommand.Parameters.Add("#Connect", txtInDate.Text + " " + fromHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.Add("#Disconnect", txtOutdate.Text + " " + toHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.Add("#Rep", repID);
dataCommand.Parameters.Add("#Reason", txtReason.Text);
dataCommand.Parameters.Add("#Contact", txtContact.Text);
dataCommand.Parameters.Add("#CaseNum", txtCaseNum.Text);
dataCommand.Parameters.Add("#Comments", txtComments.Text);
dataCommand.Parameters.Add("#PropertyID", lstProperties.SelectedValue);
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
string sqlQuery = "INSERT INTO ATI_LOG_IO (Date, Connect_Time, Disconnect_Time, ATI_Rep, Reason_For_Access, Property_Contact, Case_Number, Comments, Property_ID)";
sqlQuery += " VALUES (#Today, #Connect, #Disconnect, #Rep, #Reason, #Contact, #CaseNum, #Comments, #PropertyID)";
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection))
{
dataCommand.Parameters.AddWithValue("Today", DateTime.Today.ToString());
dataCommand.Parameters.AddWithValue("Connect", txtInDate.Text + " " + fromHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.AddWithValue("Disconnect", txtOutdate.Text + " " + toHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.AddWithValue("Rep", repID);
dataCommand.Parameters.AddWithValue("Reason", txtReason.Text);
dataCommand.Parameters.AddWithValue("Contact", txtContact.Text);
dataCommand.Parameters.AddWithValue("CaseNum", txtCaseNum.Text);
dataCommand.Parameters.AddWithValue("Comments", txtComments.Text);
dataCommand.Parameters.AddWithValue("PropertyID", lstProperties.SelectedValue);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
Copy-paste should do the trick
This usually means you haven't set the CommandText property, but in your case, you have.
You should try testing that the sqlQuery string is actually not empty at this line:
dataCommand.CommandText = sqlQuery;
P.S. As a "best practice", you may want to consider opening the connection AFTER setting up the SqlCommand object, to minimize the time spent with an open connection:
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.Add("#Today", DateTime.Today.ToString());
//...
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
Looking at your string sql query, you're not leaving a space between the "INTO" part and "VALUES" part.
...............Property_ID)";
sqlQuery += "VALUES (#Today, ..............
SHOULD BE:
...............Property_ID)";
sqlQuery += " VALUES (#Today, ..............