Error in ExecuteNonQuery command in C#, can't update database - c#-4.0

here is the code that i have written for change password in my website in C#, but it shows the error in "ExecuteNonQuery()" command..and i cant update the database with new password... i have tried many solution for that like i have check permission in windows authentication for modify the "Database" file..
-> Code in Change.aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb";
conn = new OleDbConnection(connectionString);
conn.Open();
string str1 = "select * from Student_Login where Password ='" + TextBox1.Text + "'";
OleDbCommand cmd = new OleDbCommand(str1, conn);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
OleDbConnection con1 = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb");
con1.Open();
string str = "UPDATE Student_Login SET Password=" + TextBox3.Text + "where Password= " + TextBox1.Text;
using (OleDbCommand cmd1 = new OleDbCommand(str, con1))
{
cmd1.ExecuteNonQuery();
}
Label1.Visible = true;
con1.Close();
}
else
{
Label3.Visible = true;
}
conn.Close();
}
...................
error image

It seems that there are a few syntax issues within your existing code, such as missing quotes around your parameter values when building your queries and concatenating your strings like the following line :
string str = "UPDATE Student_Login SET Password='" + TextBox3.Text + "' where Password= " + TextBox1.Text + "'";
A bigger issue here is that you aren't using SQL Parameterization, which can cause issues like this to occur (and lead to SQL Injection vulnerabilities). Consider the following code, which should resolve all of your previous issues and keep you protected against any injection-based nastiness:
// Create your connection
using (var conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb"))
{
// Build your first query
var query = "SELECT * FROM Student_Login WHERE Password = #password";
// Create a command to execute your query
using (var cmd = new OleDbCommand(query, conn))
{
// Open your connection
conn.Open();
// Add your parameter (prevents SQL Injection and syntax issues)
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
// Execute your query into a reader
using (var dr = cmd.ExecuteReader())
{
// Go through each row
while(dr.Read())
{
// Build an update query
var updateQuery = "UPDATE Student_LogIn SET Password = #password WHERE Password = #oldPassword";
// Build a new command to execute
using (var updateCmd = new OleDbCommand(updateQuery, conn))
{
// Set a parameter and execute
updateCmd.Parameters.AddWithValue("#password", TextBox3.Text);
updateCmd.Parameters.AddWithValue("#oldPassword", TextBox1.Text);
// Execute your query
updateCmd.ExecuteNonQuery();
Label1.Visible = true;
}
}
}
}
}
You can also try this version which doesn't rely on named parameters :
// Create your connection
using (var conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb"))
{
// Build your first query
var query = "SELECT * FROM Student_Login WHERE Password = ?";
// Create a command to execute your query
using (var cmd = new OleDbCommand(query, conn))
{
// Open your connection
conn.Open();
// Add your parameter (prevents SQL Injection and syntax issues)
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
// Execute your query into a reader
using (var dr = cmd.ExecuteReader())
{
// Go through each row
while(dr.Read())
{
// Build an update query
var updateQuery = "UPDATE Student_LogIn SET Password = ? WHERE Password = ?";
// Build a new command to execute
using (var updateCmd = new OleDbCommand(updateQuery, conn))
{
// Set a parameter and execute
updateCmd.Parameters.AddWithValue("#password", TextBox3.Text);
updateCmd.Parameters.AddWithValue("#oldPassword", TextBox1.Text);
// Execute your query
updateCmd.ExecuteNonQuery();
Label1.Visible = true;
}
}
}
}
}

Can you try once this...
updateCmd.Parameters.Add("#password", SqlDbType.VarChar);
updateCmd.Parameters["#password"].Value = TextBox3.Text;
updateCmd.Parameters.Add("#oldPassword", SqlDbType.VarChar);
updateCmd.Parameters["#oldPassword"].Value = TextBox1.Text;

Related

C# CommandTimeout Using statement issue

I have a method which has served me well, but now the queries have changed and I need to add a CommandTimeout to allow for the fact that some of the client machines on which this is executed are a little under-powered. The issue I'm having is the using lines as adding a CommandTimeout doesn't work.
The program itself pulls queries down from an SFTP server each night and then executes the queries against the client DB, writes the results to file then sends the results back to the SFTP server.
I can't improve the efficiency of the query (read only access) on the client machines, so I'm stuck with this method.
public void DumpTableToFile(string connection, string destinationFile, string QueryToExec)
{
string logDirectory = VariableStorage.logDirectory;
string Practice = VariableStorage.Practice;
try
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
using (var command = new SqlCommand(QueryToExec, conn))
using (var reader = command.ExecuteReader())
using (var outFile = File.CreateText(destinationFile))
{
string[] columnNames = GetColumnNames(reader).ToArray();
int numFields = columnNames.Length;
outFile.WriteLine(string.Join("\t", columnNames));
if (reader.HasRows)
{
while (reader.Read())
{
string[] columnValues =
Enumerable.Range(0, numFields)
.Select(i => reader.GetValue(i).ToString())
.Select(field => string.Concat("", field.Replace("\"", "\"\""), ""))
.ToArray();
outFile.WriteLine(string.Join("\t", columnValues));
}
}
}
}
catch (Exception e)
{
Program log = new Program();
log.WriteToLog(" Error: " + e);
SendEmailReport(Practice + " - Data Collection Error", " Error: " + e);
}
}
OK, found the answer. I had to remove the Using statements.
var command = new SqlCommand(QueryToExec, conn);
command.CommandTimeout = 300;
var reader = command.ExecuteReader();
var outFile = File.CreateText(destinationFile);

Command text was not set for the command object - work in other places

I'm getting the above error for some reason I can't understand. I have commented out after Connect() down to disconnect and it all runs fine, so I know the problem is there somewhere. My code is:
var sixMonth = parseInt(currentDate.getMonth() - 6);
sixMonth++;
var reviewDate = year + "-" + sixMonth + "-" + day;
var d1;
var d2 = new Date(reviewDate);
var intListViewIndex9 = 0;
Connect();
var EOF = 0;
RecordSet = new ActiveXObject("ADODB.Recordset");
//set the source
RecordSet.Source = statement;
//set the conection for the record set to use
RecordSet.ActiveConnection = ObjConnection;
//Open your RecordSet (i.e. Execute the query)
RecordSet.Open;
//declare the statement
statement = "SELECT AccessDate from screens.signoff WHERE BadgeNo = '" + BadgeNo + "'";
while (RecordSetas.EOF == false){
accessDate = RecordSet.Fields("AccessDate").Value;
d1 = new Date(accessDate);
if (d1.getTime() > d2.getTime()) {
SQL("UPDATE screens.signoff SET Recertify = '1' WHERE BadgeNo = '" + BadgeNo + "'");
}
//Move to the next record in the RecordSet
intListViewIndex9 = intListViewIndex9 + 1;
RecordSet.MoveNext;
}
//Close the RecordSet
RecordSet.Close;
//Destroy the objRecordSet object variable from memory
RecordSet = {};
disconect();
I have used this structure in other places and it works absolutely fine so I'm lost as to why this isn't.
Here are the other defined bits that are called as a part of the SQL.
var ObjConnection;
function Connect(){
ObjConnection = new ActiveXObject("ADODB.Connection");
SQLlook()
ObjConnection.Open ("DSN=SQL");
}
function disconect(){
//Close the Database Connection
ObjConnection.Close;
//Destroy the objConnection object variable from memory
ObjConnection = {};
}
ADyson was right, rather than set RecordSet.source = statement and then declare it I just set the actual SQL command after (RecordSet.Source = "Select etc etc")
RescordSetas was also a typo

invalid column name when my insert data is string,when i use int it works fine

When i replace EmerPacienti with PatientId it works fine, why happen that?
if (DropDownList3.SelectedItem.Value == "In-Pacient")
{
SqlDataAdapter Da = new SqlDataAdapter("select * from Ipacient where EmerPacienti=" + TextBox11.Text + "", cn);
//SqlCommandBuilder Cmd = new SqlCommandBuilder(Da);
DataSet Ds = new DataSet();
Da.Fill(Ds, "Ipacient");
GridView1.DataSource = Ds.Tables[0];
GridView1.DataBind();
Use sql parameters to prevent sql injection, then you also don't need to wrap it in apostrophes which is required on text columns. So this is much better:
using (var cn = new SqlConnection("insert connection string"))
using(var da = new SqlDataAdapter("select * from Ipacient where EmerPacienti=#EmerPacienti", cn))
{
da.SelectCommand.Parameters.Add("#EmerPacienti", SqlDbType.VarChar).Value = TextBox11.Text;
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
If it was an int-value use int.Parse/int.TryParse:
using (var cn = new SqlConnection("insert connection string"))
using(var da = new SqlDataAdapter("select * from Ipacient where PatientId=#PatientId", cn))
{
int patientId;
if (int.TryParse(TextBox11.Text, out patientId))
{
da.SelectCommand.Parameters.Add("#PatientId", SqlDbType.Int).Value = patientId;
// ...
}
}

no value given for required parameter

ACCESS 2013 database and i have 2 table 1 for user and table 2 for books i want to display all books that have been taken by user 1 and already did it i want to ask why there are error in query in visual studio and it works fine in MS-ACCESS 2013 query builder the database are in this link and u will find the query result image and display me no value required for parameter i think i did everything gd.
Database link
OleDbConnection connection = new OleDbConnection(#"");
OleDbCommand command = connection.CreateCommand();
OleDbDataReader reader;
try
{
string R = "SELECT * FROM Table1 INNER JOIN Table2 ON Table1.ID = Table2.Relation WHERE Table1.ID = 1";
command.CommandText = R;
connection.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
ID1.Text = reader["Table1.ID"].ToString();
fName.Text = reader["FirstName"].ToString();
lName.Text = reader["LastName"].ToString();
ID2.Text = reader["Table2.ID"].ToString();
book.Text = reader["Book"].ToString();
}
}
reader.Close();
connection.Close();
}
catch (Exception x)
{
connection.Close();
MessageBox.Show(x.Message.ToString());
}
finally
{
connection.Close();
}

data insert an retrival to/from database using checked list box

How to insert and retrieve data to/from database using checkedlistbox in c#
here is my cod eon button click event :
string CS = ConfigurationManager.ConnectionStrings["RosterFinal"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
var Sep = "";
string INSERTq = "insert into T_Entity values(#Tno,#Tname,#STime,#ETime,#Skill1,#S_Day1)";
SqlCommand cmd = new SqlCommand(INSERTq, con);
cmd.Parameters.AddWithValue("#Tno", txtTNo.Text);
cmd.Parameters.AddWithValue("#Tname", txtTNa.Text);
cmd.Parameters.AddWithValue("#STime", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#ETime", dateTimePicker2.Text);
foreach (object i in checkedListBox1.CheckedItems )
{
// cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Skill1", checkedListBox1.SelectedItem.ToString());
}
foreach (object m in cbDay.CheckedItems)
{
// cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#S_Day1", cbDay.SelectedItem.ToString());
}
con.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
It is not readind the scaller parameters and givein exception that scaller parameters skill1 must be unique
This exception is because of setting parameters "#Skill1" and "#S_Day1" multiple times for a single insert statement.
Also, in foreach loop, you are setting the same value each time, that's of no use.
I suggest you to use following code,
using (SqlConnection con = new SqlConnection(CS))
{
var Sep = "";
string INSERTq = "insert into T_Entity values(#Tno,#Tname,#STime,#ETime,#Skill1,#S_Day1)";
SqlCommand cmd = new SqlCommand(INSERTq, con);
cmd.Parameters.AddWithValue("#Tno", txtTNo.Text);
cmd.Parameters.AddWithValue("#Tname", txtTNa.Text);
cmd.Parameters.AddWithValue("#STime", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#ETime", dateTimePicker2.Text);
cmd.Parameters.AddWithValue("#Skill1", checkedListBox1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#S_Day1", cbDay.SelectedItem.ToString());
con.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
I think this may help u..
compare this code and modify as urs..
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
string query = "select employee_id,Employee_name from employee_details order by employee_name";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataAdapter sda ;
DataSet ds = new DataSet();
sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow datarow in dt.Rows)
{
checkedListBox1.Items.Add(datarow["employee_id"] + ": " + datarow["Employee_name"]);
}

Resources