retrieve data from access database - c#-4.0

I want to retrieve a path of an image from access
DataTable myTable = new DataTable();
OleDbConnection myConnection = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = "SELECT ImageName AS 'ImageName', ImagePath AS 'Path' FROM [AImages] WHERE ID='" + _ID + "'";
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myTable);
but in last line an error occurred like this: Data type mismatch in criteria expression.

I suspect the problem is with the way you pass an ID, maybe you can try this instead:
// note the ID=?
myCommand.CommandText = "SELECT ImageName AS 'ImageName', ImagePath AS 'Path' FROM [AImages] WHERE ID=?";
myCommand.CommandType = CommandType.Text;
// now a parameter
var pId = new OleDbParameter {Value = _ID};
myCommand.Parameters.Add(pId);
I hope this helps.

Related

New to SQL - Need to search more than 1 column but can't seem to get it to work with the AND OR coding

The below is the code for the single ID Column search. Can someone help me rewrite this to search other columns in the table please. I need to add LastName, Rank, and EmployerID as searchable as well:
string find = "select * from SDEmployee where (Id like '%' +#Id+ '%')";
SqlCommand cmd = new SqlCommand(find, con);
cmd.Parameters.Add("#Id", SqlDbType.NVarChar).Value = TextBox16.Text;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Id");
GridView1.DataSourceID = null;
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
Label1.Text = "Data has been found.";
I tried using the Where, AND OR lines but maybe did not write them correctly. Not sure. I am thinking this might work but need some new eyes in it to check my thinking:
string find = "select * from SDEmployee where (Id like '%' +#Id+ '%' AND 2ndColumn like #var2)";
SqlCommand cmd = new SqlCommand(find, con);
cmd.Parameters.Add("#Id", SqlDbType.NVarChar).Value = TextBox16.Text;
cmd.Parameters.Add(#var2, SqlDbType.NVarChar).Value = TextBoxVar2.Text
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Id");
GridView1.DataSourceID = null;
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
Label1.Text = "Data has been found.";

'External table is not in the expected format.' when reading excel(.xlsx) file which is saving in 2010 format?

when i am reading excel(2010) file, "External table is not in the expected format." error occurs. i am using Oledb connection to read excel file.please provide me best solution for this issue. thank you...
string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;IMEX=1;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connectionstring))
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
System.Data.DataTable dtExcelSchema;
dtExcelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string firstSheet = "";
int count = dtExcelSchema.Rows.Count;
conn.Close();
//Read Data from First Sheet
conn.Open();
DataTable dt = new DataTable();
var tempDataTable = (from dataRow in dtExcelSchema.AsEnumerable()
where !dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase")
select dataRow).CopyToDataTable();
dt = tempDataTable;
firstSheet = dt.Rows[0]["TABLE_NAME"].ToString();
if (!firstSheet.EndsWith("$"))
{
firstSheet = dt.Rows[0]["TABLE_NAME"].ToString() + "$";
}
cmd.CommandText = "select * from [" + firstSheet + "]";
string query1 = "SELECT count(*) FROM [" + firstSheet + "]";
cmd = new OleDbCommand(query1, conn);
cmd.CommandText = query1;
if (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
{
string sheetName = firstSheet.Replace(" ", "").Replace("'", "");
string query = "SELECT * FROM [" + sheetName + "]";
dtnew.TableName = firstSheet;
OleDbDataAdapter oda = new OleDbDataAdapter(query, conn);
oda.Fill(dtnew);
}
}
catch (Exception ex)
{
}
}

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

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;

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"]);
}

Excel to dataTable

I need to fetch a sheet from excel to a datatable. I first tried with LinqToExcel library, but this fetched the large numbers from the excel sheet as exponential numbers. I'm talking about big numbers like "2352143523453452334544". Only if they are formated as text it would work ok.
After that i've tried this :
OleDbConnection con = null;
System.Data.DataTable dt = null;
System.Data.DataTable dataTable1 = new System.Data.DataTable();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + UploadFileName + ";Extended Properties=Excel 8.0;";
string sql_xls;
con = new OleDbConnection(conStr);
con.Open();
//OracleDataAdapter oda = new OracleDataAdapter();
//OracleCommand cmd = new OracleCommand("select * from [Sheet1$]", con);
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheetNames = new string[dt.Rows.Count];
int i = 0;
foreach (System.Data.DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString(); i++;
}
sql_xls = "SELECT * FROM [" + excelSheetNames[0] + "]";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql_xls, conStr);
System.Data.DataSet myDataSet = new System.Data.DataSet();
dataAdapter.Fill(myDataSet, "ExcelInfo");
dataTable1 = myDataSet.Tables["ExcelInfo"];
This one returned the same values in the same conditions as null.
Isn't there a simple way to fetch data from a excel file as it is? No conversions, no nothing. Just take it all as a string, and put it into a datatable ?
This is what i used and it worked for me:
private DataTable LoadXLS(string strFile, String sheetName)
{
DataTable dtXLS = new DataTable(sheetName);
try
{
string strConnectionString = "";
if(strFile.Trim().EndsWith(".xlsx"))
{
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if(strFile.Trim().EndsWith(".xls"))
{
strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
OleDbConnection SQLConn = new OleDbConnection(strConnectionString);
SQLConn.Open();
OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
string sql = "SELECT * FROM [" + sheetName + "$]";
OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
SQLAdapter.SelectCommand = selectCMD;
SQLAdapter.Fill(dtXLS);
SQLConn.Close();
}
catch (Exception)
{
throw;
}
return dtXLS;
}
But you can try to export to CSV as well:
LinqToCSV

Resources