This is my code, I has put this function in my case there, why can I still not retrieve any data from my MS Access database? Is it the database problem? Or because my MS Access is version 2013 which is a pirated version?
public void display(event_detail e)
{
string path = Directory.GetCurrentDirectory();
string connstring = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + #"\GameMuseumManagementSystem.mdb";
OleDbConnection conn = new OleDbConnection(connstring); //Create connection
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * from Event WHERE Event_Title ='" + PassName + "'", conn); //Create command
cmd.Connection = conn; //command connect to database
OleDbDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
e.notxt.Text = (myReader["Event_No"].ToString());
//e.notxt.ReadOnly = true;
e.titletxt.Text = (myReader["Event_Name"].ToString());
//e.titletxt.ReadOnly = true;
e.datedetail.Text = (myReader["Event_Date"].ToString());
//e.datedetail.ReadOnly = true;
e.detailtxt.Text = (myReader["Event_detail"].ToString());
//e.detailtxt.ReadOnly = true;
}
}
Related
There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?
protected void Page_Load(object sender, EventArgs e) {
rno.Text = Request.QueryString["rno"];//rno is a textbox
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "select fname from table1 where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()) {
fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
}
reader.Close();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
protected void modify_Click(object sender, EventArgs e) {
fName.ReadOnly = false;
}
protected void savechanges_Click(object sender, EventArgs e) {
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update table1 set fname=#fname where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", sfname);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
I have tried your code which executed fine and updated database table as well.
I have tried like below :
string connectionString = #"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update TestTable set fname=#fname where rno =rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", "Test");
command.Parameters.AddWithValue("#rno", "rno");
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
Another way I have tried.
using (SqlConnection connection = new SqlConnection(connectionString ))
{
connection.Open();
var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";
using (SqlCommand cmd = new SqlCommand(queryText, connection))
{
responseResults = await cmd.ExecuteNonQueryAsync();
}
connection.Close();
}
Hope it would help
After searching for a while, I found out that this code was executing perfectly. The only problem was that everything was inside the page_Load() method and thus the page was reloading everytime I updated the database and thus removing the small window to edit the textboxes. The appropriate solution was to associate this code with some button event rather than with the page_Load() event.
Below is my code, any help will be greatly appreciated
:The Microsoft Office Access database engine could not find the object 'Breach'. Make sure the object exists and that you spell its name and the path name correctly.
public void importdatafromexcel(string excelfilepath)
{
string ssqltable = "Testing";
string myexceldataquery = "select [Case Owner],[Case Number],[Severity] from [Breach]";
try
{
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 12.0;";
string ssqlconnectionstring = "Persist Security Info=False;Integrated Security=true;Initial Catalog=0Breach;server= CHAUDAHARI-J1-W\\SQLEXPRESS";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
}
catch (Exception ex)
{
txtProcessingStatus.Text = ex.Message;
}
}
select [Case Owner],[Case Number],[Severity] from [Breach]
Is there a worksheet named "Breach" in the Excel file you are opening? In your statement above, I believe [Breach] should be the name of the worksheet you are looking for in the Excel file you are opening.
Reword the question... the below code inserts the data into an SQL Server database, and into the correct table however, the data is not inserted correctly... here is the code
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";");
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
OleDbcon.Open();
DbDataReader dr = cmd.ExecuteReader();
string con_str = #"Data Source=ENERGYSQL\ENERGY;Initial Catalog=ProjectHandler;Persist Security Info=True;User ID=aconyon;Password=birchall";
SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
bulkInsert.DestinationTableName = "StockTable";
bulkInsert.WriteToServer(dr);
OleDbcon.Close();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
//Label1.ForeColor = Color.Green;
Label1.Text = "Successfully inserted";
}
else
{
//Label1.ForeColor = ConsoleColor.Red;
Label1.Text = "please select ther File";
}
what this code does is select the far most right column, in my example Quantity, and insert just this into the database, ignoring all other rows (A and B) do i need to change the OleDbCommand to select certain rows. A(ItemName), B(Date), C(Quantity)
use this code.
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'",
Server.MapPath(#"~\DownloadedExcelFilesOp4\myfile" + fileExt));// + "\\" +
FileUploadControl.PostedFile.FileName.ToString());
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand(("Select [Demo1] ,[Demo2] FROM [Sheet1$]"),
connection);
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
}
}
You can use query like below to get the value of any particular column.
OleDbCommand command = new OleDbCommand(("Select [Col1] ,[Col2] FROM [Sheet1$]"),
connection);
I am trying to create program in .net using C# for uploading excel file, reading it and add record excel file to the sql server database from excel data.
While doing so I have got an error: Could not find installable ISAM?
Can someone help me how to fix this problem?
Or may be provide some sample code to do such kind of assignment in different way?
protected void Button1_Click(object sender, EventArgs e)
{
String excelConnectionString1;
String fname = FileUpload1.PostedFile.FileName;
if (FileUpload1.PostedFile.FileName.EndsWith(".xls"))
{
String excelsheet;
FileUpload1.SaveAs(Server.MapPath("~/file/" + FileUpload1.FileName));
if (FileUpload1.PostedFile.FileName.EndsWith(".xls"))
{
excelConnectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/file/" + FileUpload1.FileName) + ";Extended Properties=Excel 8.0;HDR=Yes;";
OleDbConnection myEcelConnection1 = new OleDbConnection(excelConnectionString1);
myEcelConnection1.Open();
if (txtsheet.Text.Length == 0)
{
lblmsg.Text = "Please Write File Name";
}
else
{
excelsheet = "[" + txtsheet.Text + "$" + "]";
string sheet = "Select * from [" + txtsheet.Text + "$" + "]";
OleDbCommand cmd1 = new OleDbCommand(sheet, myEcelConnection1);
cmd1.CommandType = CommandType.Text;
OleDbDataAdapter myAdapter1 = new OleDbDataAdapter(cmd1);
DataSet myDataSet1 = new DataSet();
myAdapter1.Fill(myDataSet1);
int a = myDataSet1.Tables[0].Rows.Count - 1;
string name;
string dob;
for (int i = 0; i <= a; i++)
{
name = myDataSet1.Tables[0].Rows[i].ItemArray[0].ToString();
dob = myDataSet1.Tables[0].Rows[i].ItemArray[1].ToString();
SqlConnection con = new SqlConnection("Connection String for Sql Server");
con.Open();
SqlCommand command = new SqlCommand("Insert into info(name,dob)values(#valname,#valdob)", con);
command.Parameters.Add("#valname", SqlDbType.VarChar, 50).Value = name;
command.Parameters.Add("#valdob", SqlDbType.VarChar, 50).Value = dob;
command.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
}
}
}
}
}
}
There's no 64 bit version of the Jet OLEDB drivers, so if you are running this on a 64 bit OS you might need to target x86 in your .NET application and not Any CPU.
Or
This error will also be generated when the syntax of the connection string is incorrect. This commonly occurs when using multiple Extended Properties parameters. Below is an example:
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=e:\My Documents\Book20.xls;Extended Properties=""Excel 12.0;HDR=NO;IMEX=1"""
Change connection string like this
ConnectionString=" Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\NAVEEN KUMAR\DOTNET\windows\WindowsApplication1\WindowsApplication1\123.xls;Excel 12.0 Xml;HDR=YES"
What I have is my combobox on Form1.cs [Design], and i created a separate class called SQLOperations to operate my SQL stuff, how do I pass to the combobox?
public static void SQLServerPull()
{
string server = "p";
string database = "IBpiopalog";
string security = "SSPI";
string sql = "select server from dbo.ServerList";
SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
//this below doesnt work because it can't find the comboBox
comboBox1.Items.Add(dr[0].ToString());
//the rest of the code works fine
}
con.Close();
}
Instead of coupling your UI and data, why don't you simply return a set of data from your "SQLServerPull" method? The UI can use that raw data in any way it sees fit, for example, filling a ComboBox.
Why not do this
public static System.Collections.Generic.List<string> SQLServerPull()
{
System.Collections.Generic.List<string> Items = new System.Collections.Generic.List<string>();
string server = "p";
string database = "IBpiopalog";
string security = "SSPI";
string sql = "select server from dbo.ServerList";
using(SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security))
{
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
//Add the items to the list.
Items.Add(dr[0].ToString());
//this below doesnt work because it can't find the comboBox
//comboBox1.Items.Add(dr[0].ToString());
//the rest of the code works fine
}
}
//Return the list of items.
return Items;
}
Or return a DataTable
public static System.Data.DataTable SQLServerPull()
{
System.Data.DataTable dt = new System.Data.DataTable();
string server = "p";
string database = "IBpiopalog";
string security = "SSPI";
string sql = "select server from dbo.ServerList";
using(SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(sql, con))
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
dt.Load(dr);
}
}
}
return dt;
}