MySqlCommand().ExecuteReader().GetString() does not work - c#

I'm working with MySql in C# language.
I'm trying get some data out of my database.
The fields are organized like:
foo baa
38737 22222
I need to get value of foo if my hash is equal to baa
I tried this:
My code(not working)
MySqlConnection con = new MySqlConnection("Server=localhost;Database=test;Uid=user;Pwd=pass;");
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = string.Format("SELECT * FROM info WHERE baa = '{0}'", Hash); ;
cmd.Connection = con;
MySqlDataReader reader = cmd.ExecuteReader();
String res = reader.GetString(0);
I'm getting the following error:
Invalid attempt to access a field before calling Read()
Can someone point out my error?
Thanks in advance.

You are missing a reader.Read() call:
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
String res = reader.GetString(0);
//...
}

Try:
string res;
using(MySqlDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
res = reader.GetString(0);
else
res = "not found";
}
If you change the SQL command to return a single value, for example:
"SELECT foo FROM info WHERE baa = '{0}' LIMIT 1"
then you can also use cmd.ExecuteScalar():
string res = cmd.ExecuteScalar().ToString();

Related

Sql reader returning DBnull for every row

I am trying to display pictures from my SQLSEVER database on my website. My users have a picture field with a picture datatype. If the picture column is null, then I want the picture displayed to be a egg.jpg, but right now for every person their picture is egg.jpg, even if they have a picture in the database. Here is my method.
public string getImageUrl()
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection();
sc.ConnectionString = "Server =MRCOMPUTER2\\SQLEXPRESS; Database = WBL;Trusted_Connection=Yes;";
sc.Open();
System.Data.SqlClient.SqlCommand insert = new System.Data.SqlClient.SqlCommand();
insert.Connection = sc;
insert.CommandText = "SELECT profilePicture from SystemUser";
insert.ExecuteNonQuery();
SqlDataReader reader = insert.ExecuteReader();
string url = "";
while (reader.Read())
{
if ( !DBNull.Value.Equals(reader[0]))
{
url = "data:Image / png; base64," + Convert.ToBase64String((byte[])reader[0]);
}
else {
url = "images/egg.jpg";
}
}
return url;
}
Your code returns the image for the last user in your table.
Here:
insert.CommandText = "SELECT profilePicture from SystemUser";
you select all users from the table (not just the one you currently show). Then:
while (reader.Read())
{
...
url = ...
...
}
you re-assign url inside every iteration of your while loop. This is semantically equivalent to:
url = ... /* The value determined from the last record of the reader. */
Thus, all your users show the same image - the one of the last user in your table.
You SELECT statement is attached into a ExecuteNonQuery?
Take it off.
Just perform the READER statement...
Try this:
static void Main(string[] args)
{
string connectionString = "Server=.;Database=AA;Trusted_Connection=True;";
/*
CREATE TABLE [dbo].[SystemUser]
(
[ProfilePicture] [varbinary](max) NULL
)
*/
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = #"
INSERT [AA].[dbo].[SystemUser] ([ProfilePicture]) VALUES (#ProfilePicture);
INSERT [AA].[dbo].[SystemUser] ([ProfilePicture]) VALUES (NULL);
";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
byte[] bytes = File.ReadAllBytes(#"1.jpg");
command.Parameters.AddWithValue("#ProfilePicture", bytes);
connection.Open();
command.ExecuteNonQuery();
}
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = #"
SELECT TOP 1000 [ProfilePicture] FROM [AA].[dbo].[SystemUser];
";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
}
var rows = ds.Tables[0].Rows.Cast<DataRow>();
foreach (DataRow row in rows)
{
byte[] bytes = row.Field<byte[]>(0);
if (bytes != null)
{
string fileName = Guid.NewGuid().ToString("N") + ".jpg";
File.WriteAllBytes(fileName, bytes);
}
}
}
Can you try using the name of the column such as
var Val = (String)reader["column name"];
Also, try something like this to test:
while (reader.Read())
{
var testVal = reader.GetString(0);
Var testVal2 = reader.GetString(1);

c# query to txt

I was reading the example here:
https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx
And wanted to do a test reading that select and writing it into a file:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
System.IO.File.WriteAllText(#"C:\stupidtest\customers.txt", reader.ReadToEnd());
sqlConnection1.Close();
But i can't because 'SqlDataReader' does not contain a definition for 'ReadToEnd' and no extension method 'ReadToEnd' accepting a first argument of type 'SqlDataReader' could be found.
So how can i get that simple select into a txt file with an output like this one?
dasdgdsgsdg asgasg sadgasdgasdg agdsfg
sdasdgasdgasgg sdfasdfa sadfasdfasdgasdgasdg sadgasgdgda
a asd gdgasdg asdfgghh
If i use:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\stupidtest\customers.txt"))
{
while (reader.HasRows)
{
while (reader.Read())
{
file.WriteLine(reader.GetString());
}
reader.NextResult();
}
could i achieve it?
something like this:
static string ReadToEnd(this SqlDataReader rdr){
StringBuilder MyStringBuilder = new StringBuilder();
while (rdr.Read())
{
String line = "";
for(int i=0;i<rdr.FieldCount;i++)
{
line+=rdr.GetString(i)+#"\t";
}
MyStringBuilder.AppendLine(line);
}
return MyStringBuilder.ToString();
}

Check if login details match those in database

I am creating a login system but I dont know how to handle the login information (username and password)
Here is my code:
MySqlConnection connection = new MySqlConnection(MySQLConnection);
connection.Open();
string result = string.Empty;
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM users WHERE nick="+nick.Text+" AND password="+pass.Text+" LIMIT 1;";
MySqlDataReader dataReader = cmd.ExecuteReader();
result = (string)cmd.ExecuteScalar();
connection.Close();
if (result.Length!=0)
{
int id;
label3.Text = "Loged.";
dataReader.Read();
id = Convert.ToInt32(dataReader[0]);
game g = new game();
g.label1.Text = Convert.ToString(dataReader[1]);
g.label84.Text = Convert.ToString(id);
this.Hide();
g.Show();
}
else
{
label3.Text = "Bad information.";
}
This doesnt work: how do I check if the user exists with this information(username and password) and that the details are valid?
Following should be done:
Use Parameterized Query and using statement
Use only MySqlDataReader no need of ExecuteScalar
Check if dataReader.HasRows
Read values from reader and perform required action.
Code:
using (MySqlConnection connection = new MySqlConnection(MySQLConnection))
{
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM users WHERE nick=#nick AND password=#pass LIMIT 1;";
cmd.Parameters.AddWithValue("#nick", nick.Text);
cmd.Parameters.AddWithValue("#pass", pass.Text);
using (MySqlDataReader dataReader = cmd.ExecuteReader())
{
if (dataReader.HasRows)
{
label3.Text = "Loged.";
dataReader.Read();
int id = Convert.ToInt32(dataReader[0]);
game g = new game();
g.label1.Text = Convert.ToString(dataReader[1]);
g.label84.Text = id.ToString();
this.Hide();
g.Show();
}
else
{
label3.Text = "Bad information.";
}
}
}
I think the problem is your select statement. You have to use single quote in where condition for the string data types
Try the following query
cmd.CommandText = "SELECT * FROM users WHERE nick='"+nick.Text+"' AND password='"+pass.Text+"' LIMIT 1;";
Also you can make the query parameterized, which is more efficient.

Select sql how to get value DataReader

I want to retrieve value /miejsca/, but I don't how it works. For example please show me how selecting value define as variable or how to show it in textbox.
At this point I recieve "System.Data.SqlClient.SqlDataReader" in textbox.
SqlDataReader reader;
cn.Open();
cmd.CommandText = ("SELECT miejsca FROM oferty WHERE oferty.idoferty = #rezerw");
cmd.Parameters.AddWithValue("#rezerw", rezerw);
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
reader = cmd.ExecuteReader().Read
string rs = Convert.ToString(reader);
TextBox1.Text = rs;//at this point i recieve "System.Data.SqlClient.SqlDataReader" in textbox
cn.Close();
If you are reading a single row and a single column: just use ExecuteScalar():
string rs = (string)cmd.ExecuteScalar();
But to answer your question, the normal usage is:
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// read a row, for example:
string foo = reader.GetString(0);
Console.WriteLine(foo);
}
}

Requesting Single Record from DataBase in Json Format using WCF Rest

public Users GetUserById(string _id)
{
MySqlConnection conn = new MySqlConnection(connstr);
conn.Open();
string sql = ("select * from Books where id = " + _id);
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
Users obj = new Users();
if (reader.Read())
{
obj.id = Convert.ToInt32(reader[0]);
obj.UserName = reader[1].ToString();
}
reader.Close();
conn.Close();
return obj;
}
I am puuling the info in Json Format but
Out Put for this is: {"UserName":"John","id":1}
Expected Out put is: [{"UserName":"John","id":1}]
I am missing the Square braces for the record
Whats the problem with my code?
Your expected output i.e. [{"UserName":"John","id":1}]
represents the List of Users object.
So if you want such output should return from your function then you just need to return a List of user from your function.
But as your function name GetUserById, I think it should return single user( So I don't know why are trying to return an array of users from this)
But anyway you can get the expected output in this way
public List<Users> GetUserById(string _id)
{
MySqlConnection conn = new MySqlConnection(connstr);
conn.Open();
string sql = ("select * from Books where id = " + _id);
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
List<Users> users=new List<Users>();
Users obj = new Users();
if (reader.Read())
{
obj.id = Convert.ToInt32(reader[0]);
obj.UserName = reader[1].ToString();
users.Add(obj);
}
reader.Close();
conn.Close();
return users;
}
Now whenever this users convert into json format, it will return the expected output.

Categories