SqlCommand cmd1 = new SqlCommand("INSERT INTO Userinformation(Access)
VALUES("+nameAccess.Text+") WHERE User_ID='"+userIdaccess.Text+"'",con);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("User Access Blocked");
}
dr.Close();
It is giving an exeption as below:
"incorrect syntax near keyword 'WHERE' "
Use parametrized queries to avoid SQL injection and also ensure to properly encode the query and also wrap your IDisposable resources in using statements to avoid leaking unmanaged handles. Also an INSERT SQL statement doesn't have a WHERE clause:
using (SqlCommand cmd1 = new SqlCommand("INSERT INTO Userinformation(Access) VALUES(#NameAccess)", con))
{
cmd1.Parameters.AddWithValue("#NameAccess", nameAccess.Text);
using (SqlDataReader dr = cmd1.ExecuteReader())
{
if (dr.Read())
{
MessageBox.Show("User Access Blocked");
}
}
}
Everytime you use the + operator when building a SQL query you are doing it wrong.
You can't do INSERT .. VALUES... WHERE, that's why. It's invalid syntax.
Insert Syntax : http://msdn.microsoft.com/en-us/library/ms174335.aspx
INSERT INTO doesn't have a WHERE clause. You can either do an UPDATE... WHERE your clause is met or insert both user info and user id as a new row.
try this code :
SqlCommand cmd1 = new SqlCommand("INSERT INTO Userinformation(Access)
VALUES('"+nameAccess.Text+"')",con);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("User Access Blocked");
}
dr.Close();
Insert query have no where clause
Related
Currently working on a small tool for the company I am working at which shall handle the database. I have several classes handling various SQL functions, but whenever I try to put specific data from the database into a datagridview I get the Exception.
SQL function:
public class OUsersDB
{
SqlConnection conn = new SqlConnection("Connection Information");
public SqlDataReader Select()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT au.ApplicationId, au.UserId, au.UserName, au.MobileAlias, au.LastActivityDate, au.Name, sms.number, am.email FROM aspnet_users AS au " +
" JOIN aspnet_membership AS am ON au.userid=am.userid " +
" JOIN smsphonebooks AS sms ON au.name=sms.name";
SqlDataReader ur = cmd.ExecuteReader();
return ur;
}
}
Winform datagrid function
public void Usersdb()
{
OUsersDB oudb = new OUsersDB();
SqlDataReader ur = oudb.Select();
myDataUsers.Rows.Clear();
while (ur.Read())
{
object[] objUsers = {
ur["au_ApplicationId"].ToString(),
ur["au_UserId"].ToString(),
ur["au_UserName"].ToString(),
ur["au_MobileAlias"].ToString(),
ur["au_LastActivityDate"].ToString(),
ur["au_Name"].ToString(),
ur["au_Phone"].ToString(),
ur["au_Email"].ToString(), };
myDataUsers.Rows.Add(objUsers);
conn.Close();
}
I have a similar sql function and object array futher up in the code which loads just fine, but once reaching this part I get the Exception on the
ur["au_ApplicationId"].ToString(),
It simply says
System.IndexOutOfRangeException: 'au_ApplicationId'
Change the obj to read the columns without the alias. You use aliases only to reference the columns in the query, but the output of the query won't have the aliases.
while (ur.Read())
{
object[] objUsers = {
ur["ApplicationId"].ToString(),
ur["UserId"].ToString(),
ur["UserName"].ToString(),
ur["MobileAlias"].ToString(),
ur["LastActivityDate"].ToString(),
ur["Name"].ToString(),
ur["Phone"].ToString(),
ur["Email"].ToString(), };
myDataUsers.Rows.Add(objUsers);
conn.Close();
}
Check if you get ANY object, maybe you get nothing at all.
You can try this:
https://stackoverflow.com/a/8656011/8512753
or remove the table aliases
ur["au_ApplicationId"].ToString(),
becomes
ur["ApplicationId"].ToString(),
and try assigning concrete values to the columns returned in your SQL
SELECT ApplicationId = au.ApplicationId, ...
Regarding the IndexOutOfRangeException, that's due to trying to access a column that doesn't exist in the reader. Not sure why you're prefixing columns with "au_" when the SELECT statement is not doing this.
I would use SqlDataAdapter instead and add add this method to OUsersDB.
public void FillTable(DataTable table)
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT au.ApplicationId, au.UserId, au.UserName, au.MobileAlias, au.LastActivityDate, au.Name, sms.number, am.email FROM aspnet_users AS au " +
" JOIN aspnet_membership AS am ON au.userid=am.userid " +
" JOIN smsphonebooks AS sms ON au.name=sms.name";
using(var adapter = new SqlDataAdapter(cmd))
adapter.Fill(table)
}
Change calling code to:
public void Usersdb()
{
OUsersDB oudb = new OUsersDB();
myDataUsers.Rows.Clear();
oudb.FillTable(myDataUsers);
}
Or here's a simple fix, instead. Change your SELECT statement to alias column names as the code is expecting.
SELECT au.ApplicationId as au_ApplicationId, au.UserId as au_UserId, au.UserName as au_UserName,
au.MobileAlias as au_MobileAlias, au.LastActivityDate as au_LastActivity, au.Name as au_Name,
sms.number as au_Phone, am.email as au_Email -- REST OF QUERY UNCHANGED
After I try to output the password in the dataGrid, from the given Username in the txt_Username textbox, I get this error message:
MySql.Data.MySqlClient.MySqlException: "Unknown column 'Test' in 'where clause'"
MySqlDataAdapter da = new MySqlDataAdapter("Select Password from tbl_anmeldedaten Where Username=" + txt_Username.Text, con);
da.SelectCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
The exact cause of the error is that you are trying to execute the following query:
SELECT Password
FROM tbl_anmeldedaten
WHERE Username = Test;
Does it look like Test should have single quotes around it? Yes, it should, and you could add that to your raw query. But, concatenating a query like this in C# leaves open the possibility for SQL injection. A much better approach is to use prepared statements:
string sql = "SELECT Password FROM tbl_anmeldedaten WHERE Username = #val1";
MySqlCommand cmd = new MySqlCommand(sql, MySqlConn.conn);
cmd.Parameters.AddWithValue("#val1", txt_Username.Text);
cmd.Prepare();
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// consume a record in the result set
}
You are using string concatenation which is a vector for SQL injection attacks. Perhaps the username in the text field is doing some SQL which it shouldn't be allowed to (for instance '' OR Test=1. There are plenty of resources on using parameterized queries which should remedy the problem.
i have this sql command
string myreg = "select registration_no from truck where truck_id ='" + truckID + "'";
MySqlCommand cmd = new MySqlCommand(myreg, conn);
i want to put the value of myreg to my RegistrationNo.Text label.
i have this RegistrationNo.Text = myreg; and it displays select registration_no from truck where truck_id on my page
You need to read something about the workings of ADO.NET and its providers.
To get the result of that query in your textbox you need
Open a connection to your MySql Server
Prepare a command to send to the Server
Get back the result
Write the result to your textbox
All these passages requires the use of specific classes and some code to glue everything together
// Prepare your command using a parameter placeholder
string myreg = "select registration_no from truck where truck_id =#id";
// Build the connection to the server and build the command to execute
using (MySqlConnection cnn = new MySqlConnection(.... the connection string that identifies your server and db ))
using (MySqlCommand cmd = new MySqlCommand(myreg, cnn))
{
// Open the connection
cnn.Open();
// Add the parameter expected
cmd.Parameters.Add("#id", MySqlDbType.VarChar).Value = truckID;
// Execute the command and get back the return value (if found)
object result = cmd.ExecuteScalar();
// Check if the ExecuteScalar has returned something
if(result != null)
RegistrationNo.Text = result.ToString();
else
... message to your user about the failed search ...
}
PS. I have assumed that your variable truckID is a string because in your original code you have passed it between single quotes, but if it is an integer then you need to modify the parameter type to MySqlDbType.Int32
Also, I have used the ExecuteScalar method instead of ExecuteReader because I think that your query returns just a row with a single column and for this task it is better to use ExecuteScalar
You can use datareader also.See MSDN documentation here.
using (connection)
{
SqlCommand command = new SqlCommand(
"SQL Query",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
I just learn how to connect C# and PostgresSQL.
I want to INSERT data from tb1(Textbox) and tb2 to database. But I don't know how to code
My previous code is SELECT from database.
this is my code
private void button1_Click(object sender, EventArgs e)
{
bool blnfound = false;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=admin123;Database=Login");
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM login WHERE name='" + tb1.Text + "' and password = '" + tb2.Text + "'",conn);
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
blnfound = true;
Form2 f5 = new Form2();
f5.Show();
this.Hide();
}
if (blnfound == false)
{
MessageBox.Show("Name or password is incorrect", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
dr.Close();
conn.Close();
}
}
So please help me the code.
First off, you need to use the ExecuteNonQuery method rather than ExecuteReader since you're executing an INSERT rather than a SELECT statement. So, something like:
NpgsqlCommand cmd = new NpgsqlCommand("insert into table1 values(1, 1)", conn);
cmd.ExecuteNonQuery();
The ExecuteNonQuery method will also return the number of rows affected if that's important for you.
Second, you need to use SQL parameters rather than building an unsafe SQL string.
Use:
cmd.Parameters.Add(new NpgsqlParameter("name", tb1.Text));
cmd.Parameters.Add(new NpgsqlParameter("pw", tb2.Text));
To add a parameter to your query. You can now refer to it in your INSERT statement with :name or :pw, for example:
NpgsqlCommand cmd = new NpgsqlCommand("insert into login (Name, Password) values(:name, :pw)", conn);
cmd.ExecuteNonQuery();
Lastly, you might be interested in using an ORM rather than executing raw SQL statements. I'd check into the .NET Entity Framework or Castle Active Record, which is built on NHibernate. These libraries will allow you to query, update, create and delete data within your database without writing the actual SQL statements involved. It's a great way to get started, and will simply your code quite a bit!
i have a question if you please help me i have an error
Must declare the scalar variable
"#Deitails".
and i can not find out whats the problem since i am not aware what Scalar is about
var sqlCon = new
SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
// GET CONFERENCE ROLE ID
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlCon;
cmd.CommandText = "select Conference_Role_ID from AuthorPaper
where Paper_ID = #PaperId";
cmd.Parameters.AddWithValue("#PaperId",
paperId);
cmd.Connection.Open();
string ConferenceRoleId = cmd.ExecuteScalar().ToString();
cmd.Connection.Close();
cmd.Dispose();
string query2 = #"insert into
ReviewPaper(Overall_Rating,Paper_id,Conference_role_id,Deitails)
values(0,#paperId,#ConferenceRoleId,#Deitails);select
SCOPE_IDENTITY() as RPID";
cmd = new SqlCommand(query2, sqlCon);
cmd.Parameters.AddWithValue("#paperId",
paperId);
cmd.Parameters.AddWithValue("#ConferenceRoleId",
ConferenceRoleId);
string ReviewPaperId;
try
{
cmd.Connection.Open();
ReviewPaperId = cmd.ExecuteScalar().ToString();
cmd.Connection.Close();
}
catch (Exception ee) { throw ee; }
finally { cmd.Dispose(); }
thanks
You have a SQL query with a parameter named Details, but you forgot to add the parameter.
You have a line of code which says
string query2 = #"insert into ReviewPaper(Overall_Rating, Paper_id,
Conference_role_id, Deitails) values (0,#paperId,#ConferenceRoleId,#Deitails);
select SCOPE_IDENTITY() as RPID";
You provide the parameters #paperId, #ConferenceRoleId and #Deitails for the values for the insert statement. Later you specify the value for the first two parameters, but not #Deitails:
cmd.Parameters.AddWithValue("#paperId", paperId);
cmd.Parameters.AddWithValue("#ConferenceRoleId", ConferenceRoleId);
You need to add a similar line to add the value for #Deitails so that SQL server knows what to do with it. The error you are getting is coming from SQL server because by not adding a value for #Deitails in your C# code, it is not being declared for you in the SQL code which is sent to the server.
To answer your other question, 'Scalar' in this case means that the variable #Deitails represents a single value.