I have two functions and one is working perfectly and the other is not, the code is the same apart from that the non functioning code has a WHERE in the database request, I just cant get it to work and I am desperate. The cID is a string given to the function and thats the ONLY thing that is correct at the moment
Geotag c = new Geotag();
String myConnection = WebConfigurationManager.ConnectionStrings["mydatabase"].ConnectionString;
MySqlConnection myConn = new MySqlConnection(myConnection);
String strSQL = "SELECT Id,geotag,item,date,nameofplace FROM geolist WHERE Id = 'cID';";
MySqlCommand myCommand = new MySqlCommand();
myCommand.Connection = myConn;
myCommand.CommandText = strSQL;
try
{
myConn.Open();
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
myReader.Read();
while (myReader.Read())
{
my reader is empty so it skips and moves on....why? i tried what i belive is everything, like without ' ' around the cID string.
If I remove the WHERE = cID I will directly be given an object back that is the first in the list so I know the code works. The database has the matched string and even if I hard code the string into the WHERE it still wont work so its something else I am missing here.
You are comparing an Id field, so you'll have probably one record back but you are calling the Read method twice
myReader.Read();
while (myReader.Read()) // <--- empty
Related
I'm trying to get the value of a Field (User Access level it's 1 or 2 in string format) after login
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dsms.accdb");
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT AL From Users WHERE Username='" + textusername.text + "'", connection);
reader = command.ExecuteReader();
if( reader.HasRows)
{
MessageBox.Show("success","status");
label1.Text = reader.GetString(1);
}
else
MessageBox.Show("failur", "status");
connection.Close();
I did execute the code in Access and it's was totally fine
but in the program, it says "No data exist for the row/column"
The main problem in your code is the fact that you need to call reader.Read() to get anything out from a DataReader. Just calling HasRows doesn't position the reader on the first record of your query.
There are other problems in your code.
Disposable objects like connections, commands and readers should be created in a using statement to ensure proper disposition after use and because you have only one field in your query, you should use the index 0 to retrieve it not 1.
Finally the most important one. You should NEVER concatenate strings to build an sql query. In this way a malicious user could write anything in your textbox, even valid sql commands that could be executed against your database. It is called Sql Injection and if you search for these terms you will find very detailed discussions about it. However, to avoid this problem (and others like parsing input with apostrophes) you use a parameterized query like below.
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand("SELECT AL From Users WHERE Username=#name", connection);
{
connection.Open();
command.Parameters.Add("#name", OleDbType.VarWChar).Value = txtusername.text;
using(OleDbDataReader reader = command.ExecuteReader())
{
if( reader.Read())
{
MessageBox.Show("success","status");
label1.Text = reader.GetString(0);
}
else
MessageBox.Show("failur", "status");
}
}
As I am new to coding I have to get an id from user and compare it to a table from students that contains a foreign key of sectionid. I would really appreciate if you help me what to do next I have searched but I'm not understanding anything.
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string sectionID)
{
int x = Int32.Parse(sectionID);
ConnectionManager connManager = new ConnectionManager();
SqlConnection conn = connManager.GetConnection();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student Where sectionid = " + x;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
Although you MIGHT be close (not knowing all your tables), I would finish what you have using a SqlDataAdapter. That does a bunch of the work for you when loading into a table.
replace your "cmd.ExecuteNonQuery()" line with something like.
var sda - new SqlDataAdapter();
sda.Command = cmd;
var tbl = new DataTable();
sda.Fill( tbl );
This should pull down all records and put into a datatable object for you. Then you can go through each record and do whatever you need.
Also, fix your parameters. if expecting a number, do so. But from a web post, everything comes in as string and you need to parse as you have done. use int.TryParse() command (read up on that), to prevent crash if some bad text comes in unexpectedly.
Finally fix your query now and all future to prevent sql-injection. use place-holders and then your parameter, such as
cmd.CommandText = "Select * From Student Where sectionid = #parmSectionID";
cmd.Parameters.AddWithValue( "parmSectionID", x );
Dont add the "#" to the string representation in the parameters line.
Definitely read-up on more SQL commands throughout S/O and also SQL-Injection especially this early on in your development. Dont start with bad techniques that will bite you in the long run.
So im having problem gettin some data in to the database.. Im really stuck, im quite new to c# and have not learned all keywords yet, im not getting any errors just some nothing adds to my database.
textBox2.Text = myPWD;
MySqlConnection conn = new MySqlConnection("test")
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES ('values = #val')";
MySqlCommand data = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
SelectCommand.Parameters.AddWithValue("#val", this.textBox2.Text);
conn.Closed()
Manipulate the concatenation of value in passing of parameters. Don't do it inside sql statement.
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES (#val)";
// other codes
SelectCommand.Parameters.AddWithValue("#val", "values = " + this.textBox2.Text);
the reason why the parameter is not working is because it was surrounded by single quotes. Parameters are identifiers and not string literals.
The next problem is you did not call ExecuteNonQuery() which will execute the command.
Before closing the connection, call ExecuteNonQuery()
// other codes
data.ExecuteNonQuery();
conn.Close();
You should Google around and you will receive lots of content
You need to run ExecuteNonQuery
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('11','seed');", con);
cmd.ExecuteNonQuery();
cmd.Close();
When I run the following code:
query = "select count(*) from table where name = '?name'";
MySqlConnection connection =
new MySqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
connection.Open();
MySqlCommand command = new MySqlCommand(query,connection);
command.Parameters.Add("?name", name);
Int32 number = command.ExecuteScalar();
number is always zero, even when cast to an int.
I have tried converting it to int64, no dice. I have tried command.Prepare(). I have tried using Convert.ToInt32() and every other variation. I have tried just about everything under the sun including quoting verbatim what this suggests and I get no dice. Trying to cast the object as an integer, as a long, as an int32, none of this seems to work. These results are always 0 or cause a MySQL error.
EDIT: Stack overflow will not format that code properly in code tags, i apologize
The reason for that is because the parameter is enclose with single quote thus making it a string. Remove it and it will work,
query = "select count(*) from table where name = #name";
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
connection.Open();
MySqlCommand command = new MySqlCommand(query,connection);
command.Parameters.Add("#name", name);
for better code,
use using for proper object disposal
using try-catch block for proper handling of exceptions
code snippet,
query = "select count(*) from table where name = #name";
string connString =ConfigurationManager.ConnectionStrings["mydb"].ToString();
using(MySqlConnection connection = new MySqlConnection(connString))
{
using(MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.Add("#name", name);
try
{
connection.Open();
// other codes
}
catch(MySqlException ex)
{
// do somthing with the exception
// don't hide it
}
}
}
Ok either I'm really tired or really thick at the moment, but I can't seem to find the answer for this
I'm using ASP.NET and I want to find the amount of rows in my table.
I know this is the SQL code: select count(*) from topics, but how the HECK do I get that to display as a number?
All I want to do is run that code and if it = 0 display one thing but if it's more than 0 display something else. Help please?
This is what I have so far
string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand topiccmd = new SqlCommand(selectTopics, con);
if (topiccmd == 0)
{
noTopics.Visible = true;
topics.Visible = false;
}
but I know I'm missing something seriously wrong. I've been searching for ages but can't find anything.
PHP is so much easier. :)
Note that you must open the connection and execute the command before you can access the result of the SQL query. ExecuteScalar returns a single result value (different methods must be used if your query will return an multiple columns and / or multiple rows).
Notice the use of the using construct, which will safely close and dispose of the connection.
string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand topiccmd = new SqlCommand(selectTopics, con);
con.Open();
int numrows = (int)topiccmd.ExecuteScalar();
if (numrows == 0)
{
noTopics.Visible = true;
topics.Visible = false;
}
}
ExecuteScalar is what you're looking for. (method of SqlCommand)
Btw, stick with C#, there's no way PHP is easier. It's just familiar.
You need to open the connection
This might work :
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "select count(*) from topics";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
Similar Question: C# 'select count' sql command incorrectly returns zero rows from sql server