Sorry for not putting the question in the title, the real problem is that I can't see an issue with my code but it's not producing what I want it to.
So I've written some code which is meant to take the database's Password field and inspect its value then store that value as a string within a password variable. In SQL Management studio the value is 'MyPass', that's what I'm expecting to get when I print out the password variable as a MessageBox. Instead I get two boxes, 'password' and then 'password123'. The only column within the table: Login, is one called Password.
Here is the using statement:
using(SqlConnection con = new SqlConnection(connectionString))
{
string query = "SELECT Password FROM LoginInfo";
con.Open();
//SqlCommand to be executed against my DB with the query text and the connection object.
SqlCommand myCommand = new SqlCommand(query, con);
//Sends CommandText to connection. Creates a
SqlDataReader read = myCommand.ExecuteReader();
while(read.Read())
{
//Convert read to IDataRecord.
ReadSingleRow((IDataRecord)read);
}
read.Close();
}
I apologize if my comments are incorrect, I wrote them down because they help me think.
You can read my interpretation of the code below and tell me what's wrong with my thinking process or you can just scour the code samples for errors.
My Interpretation (If you'll indulge me):
So, in the using statement we create a connection, a query string, an SqlCommand and an SqlDataReader. Passing the SqlCommand the query string and the connection object we then set its instance equal to an SqlDataReader, named 'read' with the method ExecuteReader() which takes the command text to wherever the connection is through the connection object.
Next we use a while loop, we use the .Read() to advance the reader on to the first record, since my db only has one record 'Password' this just moves it on to that. Within while we have the method ReadSingleRow which converts the reader instance into an IDataRecord: ((IDataRecord)read).
The ReadSingleRow method:
public void ReadSingleRow(IDataRecord record)
{
UserPass = record.GetString(record.GetOrdinal("Password"));
MessageBox.Show(UserPass);
}
the IDataRecord retrieves the string value of the oridinal(ID) password. My understanding is that it looks at the value of Password: Mypass, and then stores that within the UserPass string variable. The MessageBox of course blurts out the variable as a test to see if it worked. It didn't.
So my question is the annoying: why didn't this work? Perhaps I am miss-using the IDataRecord.
Related
string constring = "datasource=127.0.0.1;port=3306;username=user;password=pass;database=raw_data";
string Query = "SELECT * FROM data WHERE symbol='" + textBox1.Text + "';";
try
{
MySqlConnection connDataBase = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand(Query,connDataBase);
connDataBase.Open();
MySqlDataReader reader = cmd.ExecuteReader();
I tried to change it many times but unsuccessfully and looked for a soloution which was not found.
Well, you have quite a few issues:
MySQL does not use an argument datasource in the connection string. Perhaps server?
We cannot tell what will happen with the string in the query variable since we don't know the contents of the text box. You should show us the contents of that variable after the concatenation.
Performing string concatenation to produce SQL as you are doing is both error prone (what happens if there's a single quote character in the string) and dangerous (someone can exploit the difficulty to push random SQL into your database). You should read about parameterized SQL queries which are easy to construct and safer to use.
The variable name Query is not a good one as it's mis-cased and may well conflict with a class name.
The name data is dangerous for a table and symbol likewise for a column name as they may well conflict with reserved words. If you must use them, enclose them in the proper identifier quotes for your database.
I'm trying to write a c sharp program where I enter data to database and read data from database
Database name is kangoojump and I have an admin table here to store id,username and password
I created a login screen for my program and want to type in my username& password and when I press the login button I want to retrieve data from the database table and compare the two and if they match give access to next form...
here is my code
MySqlCommand SelectCommand = new MySqlCommand(" SELECT username FROM kangoojump.admin where _id=1", mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = SelectCommand.ExecuteReader();
while (myReader.Read())
{
temp1 = myReader["username"].ToString();
}
I have created a username,password,temp1,temp2 of type string in my function but
when I try to run the program I get the error that " use of unassigned variable 'temp1' "
what is the problem with my code?
Thanks
Where have you defined temp1 ?
when defining temp1
do it as follows -
string temp1 = string.Empty;
The problem has to do (in part) with this line of code:
while (myReader.Read())
You and I are smart enough to know that the database query will always return a row, but the compiler is not. This because we have information that is not available to the compiler: we know there will be an admin record. The compiler can't know this. Therefore, the compiler can't guarantee that your code will ever enter the body of that while loop. This means it also can't guarantee that you will ever assign a value to the temp1 variable... hence, your potentially "unassigned variable 'temp1'": the compiler can't guarantee you've written a reasonable value to the variable yet, and you're not allowed to read from it until you do.
The easy solution is to just assign a basic value to the variable when you first declare it:
string temp1 = "";
And while we're here: never ever ever store plain-text passwords. Store one-way password hashes.
I'm doing some encryption tasks in C# and ran into an issue I can't quite figure out. I sometimes get very complex salted hash strings for users passwords and these strings, for some reason, aren't getting stored in the database correctly.
I'm using an 8-byte salt randomly generated from the RNGCryptoServiceProvider class. I am using the SHA256Managed class as my HashAlgorithm. I'm getting the string to store from the bytes created via the ASCIIEncoding.Default.GetString() method. The column these values are being stored in is of type (NVARCHAR(50), NULL). I'm storing them using the SqlCommand class.
I can see the exact string fine when stepping through my code and using the immediate window. It seems like the problem is happening when I call cmd.ExecuteNonQuery(). Should I be doing it differently than below?
string query = #"UPDATE User SET password = #password WHERE id = #userID";
cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#password", encryptedPassword);
cmd.Parameters.AddWithValue("#userID", userID);
int rowsAffected = cmd.ExecuteNonQuery();
If you require any further information, let me know. I just don't wanna put too much on here about my exact algorithm or the results of it.
Thank you.
Try using Convert.ToBase64String() instead for encoding byte array into string. This should solve your problem.
So im pretty much just messing with c# and sql databases and I created a database with a table that has 2 columns, one for username and one for password and I wanted to know how i would look up the row the username is in and get the corresponding password(cell next to it) so I could compare for a login aspx page
This is a question that is going to take you doing a bit of research. There are a plethora of tutorials on the internet on how to access data. Below I've included one way that you can return a single value for you to get started with. You'll need to include System.Data.SqlClient.
// See http://www.connectionstrings.com/ for how to build your connection string
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
Object returnValue;
cmd.CommandText = "SELECT COUNT(*) FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
returnValue = cmd.ExecuteScalar();
sqlConnection1.Close();
I lifted this example from http://msdn.microsoft.com/en-us/library/eeb84awz(v=vs.80).aspx
Wrong approach. Collect both the username and password, and look to see if there is a match in the database.
How to do it in C#? I like LINQ to SQL, even thought Microsoft recommends otherwise. Create a LINQ to SQL classes object in a C# project, call it MyContextClass, drop your database objects onto it. Then, in your code behind, write something like:
using (MyContextClass ctx = new MyContextClass) {
if (ctx.SingleOrDefault(f => f.Username == txtUsername.Text && f.Password == txtPassword.Text) != null) {
// The user got it right.
}
}
However, all the warnings about storing passwords in the comments above really do apply. Integrating those is left as an exercise for the user.
I have a DateTime record in my table in a database and I write a query to get it from the database:
string command2 = "select Last_Modified from Company_Data where Company_Name='" + DescriptionEntryForm.SelectedItem.ToString() + "'";
SqlCommand search_company2 = new SqlCommand(command2, con_string.con);
SqlDataReader company_reader2 = search_company2.ExecuteReader();
dateform.Text = company_reader2.GetValue(0).ToString();
company_reader2.Close();
But the penultimate statement throw an exception saying "Invalid attempt to read when no data is present".
How can I solve it?
Well, the immediate problem with your code is that you haven't called company_reader2.Read() to move the cursor onto the first row.
From the docs for SqlDataReader.Read:
The default position of the SqlDataReader is before the first record.
Therefore, you must call Read to begin accessing any data.
You should also note the return value of Read() which indicates whether or not you've read to the end of the record set.
Other problems:
You should put using statements around the SqlCommand and SqlDataReader, otherwise if there's an exception you won't be closing the connection. You may be able to get away with disposing the command and letting the reader just disappear automatically - but I typically dispose of both just so I don't need to think too carefully.
You're assuming that the format of date/time will be appropriate by just calling ToString with no format specifier.
You should use a parameterised SQL query to avoid SQL injection attacks.
It looks like you've executed the command, but haven't actually read from it.
company_reader2 = search_company2.ExecuteReader();
if (company_reader2 != null && company_reader2.HasRows) {
company_reader2.Read();
dateform.Text = company_reader2[0].ToString();
}