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();
}
Related
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);
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;
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"]);
}
I can add rows to my Excel spreadsheet one row at a time, but it is incredibly slow (1 minute for 400 records, even using Prepare). So, I know the Sql is valid and the DataTable is good.
The code that works:
public void InsertFromDataTable(string strSql, DataTable dtTable, string strTableName)
{
if (m_oleDbHandler == null)
{
m_oleDbHandler = new OleDbHandler(m_strConnection);
}
//Do one row at a time since the DataAdapter did not work
foreach (DataRow drRow in dtTable.Rows)
{
OleDbParmCollection cololedbParameters = new OleDbParmCollection();
foreach (DataColumn dcColumn in dtTable.Columns)
{
OleDbParameter odpParameter = new OleDbParameter("#" + dcColumn.ColumnName, drRow[dcColumn.ColumnName]);
odpParameter.ParameterName = "#" + dcColumn.ColumnName;
odpParameter.DbType = OleDbHandler.GetDbType(dcColumn.GetType());
odpParameter.Size = dcColumn.MaxLength;
odpParameter.SourceColumn = dcColumn.ColumnName;
cololedbParameters.Add(odpParameter);
}
m_oleDbHandler.ExecuteCommand(strSql, cololedbParameters, true);
}
}
}
When I try to do the same thing using a DataAdapter, it says it returns 458 rows, but there are no new rows in the spreadsheet. The code that fails:
//DataAdapter version
OleDbParmCollection cololedbParameters = new OleDbParmCollection();
foreach (DataColumn dcColumn in dtTable.Columns)
{
OleDbParameter odpParameter = new OleDbParameter();
odpParameter.ParameterName = "#" + dcColumn.ColumnName;
odpParameter.OleDbType = OleDbHandler.GetOleDbType(dcColumn.GetType());
odpParameter.DbType = OleDbHandler.GetDbType(dcColumn.GetType());
odpParameter.Size = dcColumn.MaxLength;
odpParameter.SourceColumn = dcColumn.ColumnName;
cololedbParameters.Add(odpParameter);
}
m_oleDbHandler.InsertFromDataTable(strSql, dtTable, cololedbParameters, strTableName);
and then:
public int InsertFromDataTable(string strSql, DataTable dtTable, OleDbParmCollection cololeDbParameters, string strTableName)
{
//Set every row as added so that they will be inserted
foreach (DataRow drRow in dtTable.Rows)
{
drRow.SetAdded();
}
//Update the output table
int intRows = -1;
try
{
OleDbCommand oleDbCommand = new OleDbCommand(strSql, OpenConnection());
foreach (OleDbParameter oleDbParameter in cololeDbParameters)
{
if (oleDbParameter.Value == null)
{
oleDbCommand.Parameters.Add(oleDbParameter.ParameterName, OleDbType.VarChar).Value = DBNull.Value;
}
else if (string.IsNullOrEmpty(oleDbParameter.Value.ToString()))
{
oleDbCommand.Parameters.Add(oleDbParameter.ParameterName, OleDbType.VarChar).Value = DBNull.Value;
}
else
{
oleDbCommand.Parameters.Add(oleDbParameter);
}
}
OleDbDataAdapter odaAdapter = new OleDbDataAdapter(new OleDbCommand("SELECT * FROM " + strTableName, OpenConnection()));
odaAdapter.InsertCommand = oleDbCommand;
odaAdapter.MissingMappingAction = MissingMappingAction.Passthrough;
odaAdapter.MissingSchemaAction = MissingSchemaAction.Error;
odaAdapter.TableMappings.Add(strTableName, dtTable.TableName);
foreach (DataColumn dcColumn in dtTable.Columns)
{
odaAdapter.TableMappings[0].ColumnMappings.Add(dcColumn.ColumnName, dcColumn.ColumnName);
}
intRows = odaAdapter.Update(dtTable);
}
catch (OleDbException ex)
{
LogStackTrace();
LogToDb.LogException(ex, LogToDb.c_strAppError);
LogToDb.LogMessage("OleDb error", "OleDbHandler.InsertFromDataTable error", strSql, LogToDb.c_intErrorLevelOleDb);
CancelTransactionAndClose();
throw;
}
finally
{
CloseConnection();
}
return (intRows);
}
Why would I get intRows = 458, but there are no new rows in the Excel file?
EDIT: I just did a test to see what happens if I export to a Microsoft Access .mdb (instead of Excel), and the results tell me something. I get 458 blank rows. so, I suspect I am getting 458 blank rows in Excel. So, now the question is why the rows are all blank.
Got it -- the error was in the section below. This works well for an ExecuteNonQuery, but lousy when there is no data.
foreach (OleDbParameter oleDbParameter in cololeDbParameters)
{
if (oleDbParameter.Value == null)
{
oleDbCommand.Parameters.Add(oleDbParameter.ParameterName, OleDbType.VarChar).Value = DBNull.Value;
}
else if (string.IsNullOrEmpty(oleDbParameter.Value.ToString()))
{
oleDbCommand.Parameters.Add(oleDbParameter.ParameterName, OleDbType.VarChar).Value = DBNull.Value;
}
else
{
oleDbCommand.Parameters.Add(oleDbParameter);
}
}
The corrected code, which works well with both Access and Excel is:
foreach (OleDbParameter oleDbParameter in cololeDbParameters)
{
oleDbCommand.Parameters.Add(oleDbParameter);
}
There was a second, less serious error. I used
OleDbHandler.GetOleDbType(dcColumn.GetType());
which should have been
OleDbHandler.GetOleDbType(dcColumn.DataType);
I have a problem when i m rum my code then error is occured "missing semicolon at end of sql statement."
My code is :
Code
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/mssl2.accdb;Persist Security Info=False";);
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string sql = "INSERT INTO digital(Product_Name, Product_Code, Product_Price, Product_Image, Product_Description) VALUES(#pnm, #pcod, #ppr, #pimg, #pdes) SELECT ##IDENTITY;";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#pnm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#pcod", txt_productcode.Text.Trim());
cmd.Parameters.AddWithValue("#ppr", txt_productprice.Text.Trim());
cmd.Parameters.AddWithValue("#pdes", txt_productdescri.Text.Trim());
cmd.Parameters.AddWithValue("#pimg", imgByte);
int Id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", Id);
conn.Close();
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
}
}
}
add semicolon before select ##identity. then try to excute. which means for insert statement one semicolon and for select on semi colon.
Before "SELECT ##IDENTITY", you need a semi-colon.
Technically you're creating two SQL statements.
One for insert, and one for SELECT ##IDENTITY. That's why you need a semi-colon between those two queries.