I am making a simple voting system, that when a voter is already done voting and tries to re-log in, the system will read the database and stop the voter from logging in. How can I do that?
What I have in my database :
username, password and remarks. remarks is when a voter is "Done" or "Not Voted".
What I have in my code now :
conn.Open();
SqlCommand cmd;
SqlDataReader dr;
string cmdall = "Select from Voter where username=#user and password=#pass and remarks=''"; //got no clue as to what i am going to command here..
using (cmd = new SqlCommand(cmdall, _db._conn))
{
cmd.Parameters.AddWithValue("#user", _user);
cmd.Parameters.AddWithValue("#pass", _pass);
dr = cmd.ExecuteReader();
/* Then if and else statement */
}
Please help me out, im kinda new at this.. Thanks in advance..
You query should be like:
string cmdall = "Select remarks from Voter where username=#user and password=#pass";
and then check it's value is Done :
while(dr.Read())
{
if (dr["remarks"].ToString() == "Done")
// already voted
}
as #Daniel pointed in comments better would be to use bit in database because it's suitable in your case , there is only two chances true or false
Related
I'm trying to take from a DataBase all under aged users, but when I try to, System.InvalidOperationException: 'Connection must be valid and open.'
pops up. It's a Windows Form app, so this happens when I press the button.
I have tried searching for the problem but I cant find the error. I have 5 more functions with the same syntax and they work just fine. This is the code I have:
public static List<User> Underage(MySqlConnection connection)
{
string query= string.Format("SELECT * FROM users WHERE age<18");
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataReader reader = command.ExecuteReader();
List<User> underage= new List<User>();
if (reader.HasRows)
{
User usu = new User();
while (reader.Read())
{
usu.id = reader.GetInt16(0);
usu.name = reader.GetString(1);
usu.surname= reader.GetString(2);
usu.email = reader.GetString(3);
usu.age= reader.GetInt16(4);
usu.birth = reader.GetDateTime(5);
usu.payment= reader.GetFloat(6);
underage.Add(usu);
}
}
return underage;
}
Thanks anyways and sorry if it's a stupid problem, but I just cant figure it out.
Thanks for clarifying my problem mjwills and Adyson, you were right, I forgot to open it. I have a function to open the connection which I used in every other method of my program but I forgot to add it in this one. Sorry and thank you!
I am running a C# windows application, and I get an error message when trying to use a datareader. The error message is:
"Invalid attempt to call CheckDataIsReady when reader is closed."
I used stop point and saw that the code works fine until it enters the "while" loop. Once inside, it gives the error message.
I have tried to do it without closing the previous reader, but then the message changed to something like "there is already an open reader" or some such.
Here's the code:
conn = new SqlConnection(DBConnectionString);
SqlCommand select_cmd = new SqlCommand("SELECT usrRealname, usrIsowner FROM tblUSERS WHERE usrNum = " + UserID, conn);
SqlCommand select_orders = new SqlCommand("SELECT orderNum, orderBy, orderShipadrs, orderDate, orderTotal FROM tblOrders WHERE orderDeliveryDate is NULL AND fkorderTakenbyusrnum = " + UserID, conn);
conn.Open();
SqlDataReader dr = select_cmd.ExecuteReader();
dr.Read();
CurrentUser User = new CurrentUser(Convert.ToString(dr[0]), UserID, Convert.ToBoolean(dr[1]));
DetailsLabel.Text = String.Format("Welcome {0}, ID number {1}. {2}", User.getname, UserID, User.getOwner);
dr.Close();
SqlDataReader orders = select_orders.ExecuteReader();
while (orders.Read())
{
UnfulfilledOrders CurrentOrder = new UnfulfilledOrders(Convert.ToInt32(dr[0]), Convert.ToString(dr[1]), Convert.ToString(dr[2]), Convert.ToString(dr[3]), Convert.ToInt32(dr[4]));
OrderList.Items.Add(CurrentOrder);
}
What I'd trying to do is add class (UnfulfilledOrders) type objects to a listbox (OrderList).
The thing that baffles me is that I used such a while loop in a previous form in the same app, and it worked fine there.
I really have no idea what I'm doing wrong.
I tried twiking the code, adding or removing certain parts, but nothing seems to work.
Your problem is that in your while loop you're using dr[0] instead of orders[0]. This is trying to get the value from the SqlDataReader dr.
A good way to avoid mix-ups like this would be to create the data reader in a using block.
using (var dr = select_cmd.ExecuteReader())
{
//your code here
dr.Close();
}
then
using (var orders = select_orders.ExecuteReader())
{
// your code here
orders.Close();
}
This would prevent you from accidently referencing the wrong reader because VS would give you an error saying it doesn't exist.
Your code:
dr.Close(); //<-- dr closed
SqlDataReader orders = select_orders.ExecuteReader(); // <-- Reader is "orders" here
while (orders.Read())
{
UnfulfilledOrders CurrentOrder = new UnfulfilledOrders(Convert.ToInt32(dr[0]), Convert.ToString(dr[1]), Convert.ToString(dr[2]), Convert.ToString(dr[3]), Convert.ToInt32(dr[4]));
OrderList.Items.Add(CurrentOrder);
}
dr was closed previously, do you mean "orders" instead of "dr"?
I have a SQL database named "administration" with usernames and roles.
What I would like to do with my ASP.NET application is:
once someone accesses my intranet site, I get their username using
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Then I check if that username is in my database. I assume I can do this with an IF EXISTS statement.
However I'm not sure how I would do the following: IF the user is in the database I want to display the Web Page as per their role (i.e. all pages are different Admin = see all content and buttons, User = all content no buttons).
However if their username is not in my database I will display a blank page or something along the lines of "Access Denied".
This is the way I have been asked to do it but I cant seem to work it out.
Is it possible?
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
after getting userName.
sqlconnection cn = new sqlconnection("give connectionstring");
cn.open();
sqlcommand cmd = new sqlcommand();
cmd.commandtext = "select * from "table"; // table name give.
cmd.connection = cn;
sqldatareader rdr = cmd.executereader();
while(rdr.read()){
if(stringName = rdr[columnnumber].toString());
flag = true;
}
if(flag)
//take decesion
else
// take decesion.
cn.close();
you can achieve it like this. u can use. it. bt there are some mistake in syntax i roughly write for u.
This is my first time asking a question on StackOverflow, so I apologize in advance if I ask someone improper. I couldn't find anything to help me while researching this for the past few days, so thank you in advance to anyone who tries to help.
I am making a database that allows people to register and log-in. I am using C# in VS2012.
Below is my log-in code and I am running into some trouble when testing. It iterates through everyone in the database and tells me that log-in has failed till it gets to the right user.
private void button1_Click_1(object sender, EventArgs e)
{
try
{
cn.Open();
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
SqlCommand cmd = new SqlCommand("SELECT * FROM [Users]", cn);
cmd.Connection = cn;
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
if (textBox1.Text == (reader["Username"].ToString()) && textBox2.Text == (reader["Password"].ToString()))
{
MessageBox.Show("Logged in");
}
else
{
MessageBox.Show("Login has failed. Please check your Username and Password.");
}
}
cn.Close();
}
As for my registration portion, I'm not sure if it is a VS2012 thing or what, but the information doesn't get saved into the database after I end debug and then go back to debug again.
private void button1_Click_1(object sender, EventArgs e)
{
cn.Open();
SqlCommand cm1 = new SqlCommand("INSERT INTO Users (Username, Password) VALUES (#Username, #Password)", cn);
SqlCommand cm2 = new SqlCommand("INSERT INTO Contact(Name, Address, City, State, PostalCode, Email, PhoneNumber) VALUES(#Name, #Address, #City, #State, #PostalCode, #Email, #PhoneNumber)", cn);
cm1.Parameters.AddWithValue("#Username", textBox1.Text);
cm1.Parameters.AddWithValue("#Password", textBox2.Text);
cm2.Parameters.AddWithValue("#Name", textBox3);
cm2.Parameters.AddWithValue("#Address", textBox4);
cm2.Parameters.AddWithValue("#City", textBox5);
cm2.Parameters.AddWithValue("#State", textBox6);
cm2.Parameters.AddWithValue("#PostalCode", textBox7);
cm2.Parameters.AddWithValue("#Email", textBox8);
cm2.Parameters.AddWithValue("#PhoneNumber", textBox9);
try
{
int affectedRows = cm1.ExecuteNonQuery(); //+cm2.ExecuteNonQuery();
if (affectedRows > 0)
{
MessageBox.Show("Insert Sucsess!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Insert Failed!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
cn.Close();
}
When you have a database file in you project and you build the project, the database file could be copied from the root project folder into the output (bin\debug or bin\release) folder.
This behavior is controlled by the Copy To Output Directory property of the database file.
If you have this property set to Copy Always then, every time you build your project a fresh copy of the database file is copied from the root project folder to the output directory overwriting the one already there and destroying the changes you have made in the previous debug session.
A suggested fix is to change this property to Copy Never or Copy if Newer
See a detailed explanation on MSDN at this page
For the first part of your question you could avoid to loop on every user adding a WHERE clause to your sql text. Just be aware that you should never use string concatenation to build your sql strings, instead you use ALWAYS the parameters. (Why? You avoid Sql Injection and text single quote parsing/doubling)
string sqlText = "SELECT * FROM [Users] WHERE Username = #usr AND [Password] = #psw";
SqlCommand cmd = new SqlCommand(sqlText, cn);
cmd.Parameters.AddWithValue("#usr", textbox1.Text);
cmd.Parameters.AddWithValue("#psw", textbox2.Text);
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows)
// You have found the user....
Another bit of advice. Do not store the passwords in clear text inside your database. Store always an hash of this string and, on search, compute the hash value and search for it instead of a clear password.
In order for you to get this working you will need a WHERE clause in your SELECT. However, I would not recommend to use
SqlCommand cmd = new SqlCommand("SELECT * FROM [Users] WHERE Username='" + textBox1.Text + "'", cn);
because of possible SQL injection.
Please learn how to use Stored Procedures and how to Execute them from your C# code.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Hi I'm trying to get data from a local sql service database to take the input from a user register form. but when i push the button its not recorded onto the serviceable database.
do i need to use execute non query? how would i fix this code up? thanks
using System.Data.Sql;
using System.Data.SqlClient;
namespace Paddle_Power
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
try
{
cn.Open();
MessageBox.Show("open");
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
string username = textBox1.Text;
string password = textBox2.Text;
string sqlquery = ("SELECT * FROM User WHERE Username = '" + textBox1.Text + "'");
sqlquery = "INSERT INTO [User] (Username, Password) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("Username", username);
command.Parameters.AddWithValue("Password", password);
command.Parameters.Clear();
}
}
}
Something along the lines of the following should hopefully do it. There's some room for improvement, but I at least hope it solves the problem you're having.
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True";
object queryResult = null;
using (SqlConnection cn = new SqlConnection(connection))
{
cn.Open(); // Open connection
// SELECT
using (SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE Username = #Username AND Password = #Password", cn))
{
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
queryResult = cmd.ExecuteScalar();
}
// INSERT
using (SqlCommand cmd = new SqlCommand("INSERT INTO [User] (Username, Password) VALUES (#Username, #Password)", cn))
{
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery()
}
}
You can requse the first SqlCommand object or create a new one. There's very little difference with either way you choose to do it.
queryResult is just there for storing the result of cmd.ExecuteScalar(). You can map it to an object if you want (when selecting multiple columns) or cast it to a new type (if you're selecting a single column).
The direct answer is yes, you need to execute a non query. You see, you've prepared the command but you have not issued it. jstnasn's example should be very helpful. Take note of the using statements -- these will implicitly close the command when you exit the using statement, thus ensuring that the command is always closed when done.
The same occurs for the SqlConnection -- the using helps make sure that the connection is disposed of properly. However, if your database connection string allows connection pooling, then I believe the using statement will merely kill your object, without actually killing the connection to the database. This is advantageous because you will have lower I/O overhead the next time you need to open a database connection -- you'll just be connecting to an existing TCP/IP socket rather than opening a new on.
You have no parameters, nor do you ever actually send the query to the database
// parameter placeholders defined with #parameter_name
sqlquery = "INSERT INTO [User] (Username, Password) VALUES (#username, #Password);
SqlCommand command = new SqlCommand(sqlquery, cn);
command.Parameters.AddWithValue("#Username", username);
command.Parameters.AddWithValue("#Password", password);
// This will make the query happen on the database.
// It will handle sending the parameters and all that good stuff
// http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
command.ExecuteNonQuery();