writing to MS-Access DB Issue in C sharp - c#

Hey guys, I'm just doin' practise Program to read,write data to Access DB in C# and i'm having a problem in writing data to Access DB though i'm able to read data i.e fetchin' is working fine but when i insert data my "ExecuteNonQuery" is working fine i mean without ne error but when open the Access DB the data is not there.... here is the code what m tryin' to do...
//// Function For ExecuteNonQuery
public static bool ExecuteNonQuery(string Query)
{
OleDbCommand oledbCommand = new OleDbCommand(Query, connection);
if (connection.State == ConnectionState.Open)
connection.Close();
try
{
connection.Open();
if (oledbCommand.ExecuteNonQuery() > 0)
return true;
else
return false;
}
catch (Exception)
{
return false;
}
finally
{
connection.Close();
}
}
This below code is for Adding Data which gets fired on "Add" Button Press
private void btnAdd_Click(object sender, EventArgs e)
{
simOperator.aim_network_name = txtAimNetNm.Text;
simOperator.network_id = txtOxiNetID.Text;
simOperator.network_name = txtNetName.Text;
simOperator.pack_id = txtPackID.Text;
simOperator.pack_name = txtPackName.Text;
SimOperator.Add(simOperator);
fillText();
}
public void fillText()
{
txtResult.Text = "";
SimOperator[] simOperatorList = SimOperator.GetAllOperators();
foreach (SimOperator sm in simOperatorList)
{
txtResult.Text += Program.operator_id + " " + sm.aim_network_name + " " + sm.network_name + " " + sm.network_id + " " + sm.pack_id + " " + sm.pack_name + "\r\n";
}
}
Here's the "Add" Function
string Query = string.Format("insert into {0}({2}) values({1});", calledObject.Name, PropertyValue,PropertyName);
ExecuteNonQuery(Query);
Actuall SQL query is:
insert into SimOperator(aim_network_name,network_id,network_name,pack_id,pack_name) values('FiveNet','2563','FiveNet-Kurla','1236','5236');
Yeah and My Connection String
static OleDbConnection connection = new OleDbConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
App.config file contains string as
add key="ConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AutoMobileRecharge.mdb;User Id=; Password=;Persist Security Info=True"
The thing m not getting is I have put a Text-Area just beside all the inside fields textboxes so that i can see what is getting inserted, so when insert data that text-area shows the data perfectly but when i open the access db, then theres no data in that, when i close my application and again i ran it then that text-area is empty...this sounds wierd to me.. Any one outthere have faced this kind a problem please help me out here..

Are you doing it during debug ? in that case look if there's an mdf file inside debug folder and if it contains the data you've just inserted. Vs copy some file to debug folder when you run the app in that mode. If i remember correctly there's an option to tell vs not to copy files when debugging

Related

Why my login code is not working?

I am making a user login program, My code is as follow:
private void button1_Click(object sender, EventArgs e)
{
try
{
string b = Convert.ToString(UserNameComboBox.SelectedItem);
SqlConnection DataFind = new SqlConnection(#"Data Source=.\sqlexpress; Initial Catalog=PAYROLL MANAGEMENT SYSTEM;Integrated security=true;");
DataFind.Open();
SqlCommand dmd;
dmd = new SqlCommand("SELECT COUNT(*) FROM LoginDetail where( (UserName=' " + b + "') AND (Password='" + Password.Text + "' ))", DataFind);
dmd.ExecuteNonQuery();
Int32 count = Convert.ToInt32(dmd.ExecuteScalar());
DataFind.Close();
SelectedRowNo.Text = count.ToString();
if (count == 1)
{
Form1 s = new Form1();
s.Show();
}
else
{
MessageBox.Show("Sorry You are not an authirized user");
}
}
catch { MessageBox.Show("UserName or Password not valid"); }
}
It is not giving me any output. It says that no record found, although the record exist in sql database.I am unable to understand why my program is not working.
You have one extra spaces - before the username. Remove it and it should work.
Keep in mind, though, that you're doing more or less everything wrong here. You're vulnerable to SQL Injection (think what happens when someone gives you the password ab')); DROP TABLE Users; --), and you're storing the clear password in the database, so anybody who can access your data can get all your user passwords. And since you're open to SQL injection, anybody can get your data.
https://xkcd.com/327/

C# Transfer Data from ODBC Database to Local SQL Database

I have connected to a DB through an ODBC connection. The data is on a server and I have the appropriate permissions and username/password.
I am trying to import some of the data into a local SQL database (.mdf). I suspect my SQL statement is wrong.
The idea is that when a an item is selected from a listBox that the data will be downloaded to the SQL database.
This has completely stopped any progress on my project. Please help!!!
public partial class frmNorth : Form
{
// variables for the connections
private OdbcConnection epnConnection = new OdbcConnection();
private SqlConnection tempDbConnection = new SqlConnection();
public frmNorth()
{
InitializeComponent();
// This is for the ePN DB
epnConnection.ConnectionString = #"Dsn=ePN; uid=username; pwd=myPa$$Word";
// This is for the local DB
tempDbConnection.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TempDB.mdf;Integrated Security=True";
}
private void lbxFSR_SelectedIndexChanged(object sender, EventArgs e)
{
try //For ePN
{
//This is where I need the help <--------------------
epnConnection.Open();
tempDbConnection.Open();
OdbcCommand epnCommamd = new OdbcCommand();
epnCommamd.Connection = epnConnection;
string epnQuery = "INSERT INTO " + tempDbConnection + ".tblTemp (FNCL_SPLIT_REC_ID, PROJ_ID, SALES_SRC_PRC) " +
"SELECT PROJ_FNCL_SPLIT.FNCL_SPLIT_REC_ID,PROJ_FNCL_SPLIT.PROJ_ID,PROJ_FNCL_SPLIT.SALES_SRC_PRC " +
"FROM " + epnConnection + ".PROJ_FNCL_SPLIT " +
"WHERE PROJ_ID=" + lbxFSR.Text + "";
epnCommamd.CommandText = epnQuery;
epnCommamd.CommandTimeout = 0;
epnCommamd.ExecuteNonQuery();
epnConnection.Close();
tempDbConnection.Close();
}
catch (Exception ex)
{
epnConnection.Close();
tempDbConnection.Close();
MessageBox.Show("Error " + ex);
}
}
}
This is the error that I get. The error occurs at epnCommamd.ExecuteNonQuery();
Picture of Error Message
I cant comment cause i don't have enough points so i have to put this in answers but do both of your connections actually open? I would also avoid showing passwords in your connection strings on here.
The problem is that you can't in general INSERT into one table using a SELECT from a table on another database in the way that you're attempting. If source and destination tables are on same database server (eg both on Sql Server) you have a shot at INSERT INTO db1.SourceTable ... SELECT ... FROM db2.DestinationTable.
However, since you have source table on ODBC connection and destination on Sql connection, this won't work.
You need to do it in two steps. Download your ODBC table into a C# DataTable, then upload the C# DataTable into your Sql Server table. I can't test against your databases, but I have tested a version of this code on transfers between Microsoft Access database and a Sql Server database
private void lbxFSR_SelectedIndexChanged(object sender, EventArgs e)
{
try //For ePN
{
//This is where I need the help <--------------------
// Break the operation into two parts
// The ODBC & SQL databases can't talk directly to each other.
// 1. Download ODBC table into your C# DataTable
DataTable dt;
epnConnection.Open();
string epnQuery = "SELECT FNCL_SPLIT_REC_ID, PROJ_ID, SALES_SRC_PRC " +
"FROM PROJ_FNCL_SPLIT " +
"WHERE PROJ_ID='" + lbxFSR.Text + "'";
OdbcCommand epnCommamd = new OdbcCommand(epnQuery, epnConnection);
epnCommamd.CommandTimeout = 0;
OdbcDataReader dr = epnCommamd.ExecuteReader();
dt.Load(dr);
epnConnection.Close();
// 2. Upload your C# DataTable to the SQL table
// This select query tells the SqlDataAdapter what table you want to work with, on SQL database
// The WHERE 0 = 1 clause is to stop it returning any rows,
// however you still get the column names & datatypes which you need to perform the update later
string selectQuery = "SELECT FNCL_SPLIT_REC_ID, PROJ_ID, SALES_SRC_PRC " +
" FROM PROJ_FNCL_SPLIT WHERE 0 = 1";
tempDbConnection.Open();
var da = new SqlDataAdapter(selectQuery, tempDbConnection);
var commandBuilder = new SqlCommandBuilder(da);
// The DataAdapter's `Update` method applies the contents of the DataTable `dt` to the table specified in the `selectQuery`.
// It does this via the SqlCommandBuilder, which knows how to apply updates to a Sql Database.
da.Update(dt); // Channel the C# DataTable through the DataAdapter
tempDbConnection.Close();
}
catch (Exception ex)
{
epnConnection.Close();
tempDbConnection.Close();
MessageBox.Show("Error " + ex);
}
}

Close SQL Connection on Form Close (C#)

I created a small application that queries a db2 database and returns information. I created a windows form that accepts input and returns the information from the query. My closing statement is a:
finally
{
conn.close();
}
I was curious -- does the connection (conn) actually close when I hit the little red box on the form? I searched the other questions here and the web but could not really find a definitive answer.
Here's the full try-catch-finally block (with some info obfuscated --> *****):
`try
{
conn.Open();
string queryString = String.Format("SELECT * " +
"FROM ***** " +
"WHERE USERPRF LIKE '%{0}%' " +
"ORDER BY TIMESTMP DESC " +
"FETCH FIRST 1 ROWS ONLY", userNameInput);
using (OdbcCommand com = new OdbcCommand(queryString, conn))
{
using (OdbcDataReader reader = com.ExecuteReader())
{
if (reader.Read())
{
string ***** = reader["*****"].ToString();
string ***** = reader["*****"].ToString();
string user = reader["USERPRF"].ToString();
string timeStamp = reader["TIMESTMP"].ToString();
listBox1.Items.Clear();
listBox1.Items.Add("Username: " + user);
listBox1.Items.Add("*****" + *****);
listBox1.Items.Add("*****: " + *****);
listBox1.Items.Add("Last Changed: " + timeStamp);
}
else
{
listBox1.Items.Clear();
listBox1.Items.Add("There was no data to return! Try again.");
}
}
}
}
catch (Exception ex)
{
string errorMessage = ex.Message;
}
finally
{
conn.Close();
}`
If the connection is owned by the application, then yes - it should close.
It is generally bad practice to leave a connection open for long duration's as it constitutes a security risk. (Someone could inject code into your application to reuse the open the connection, to do dodgy stuff)
using (SqlConnection cn = new SqlConnection(strConnectString))
{
// Stuff
}
I would make sure that you handle the onClosing event of your windows form, and tell it to dispose of the SqlConnection explicitly, or at least attempt to do so.
Better safe than sorry.
Note - I have heard some talk that SqlConnections can be shared in the SQLConnectionPool. If this is the case, you can modify your connection string to disable or enable ConnectionPooling.

using Service Based Database in VS2010 Ultimate

I have been working on a project related to database (.mdf). I have created some windows forms in visual studio using C#. Basically these forms work together to store, update and delete data from the Service Based Database i created.
The problem is when i build the project, it builds fine, no errors. It inserts a data provided from textboxes to the datagridview too as intended. But as soon as i stop the current debugging, and then rerun it again, all the data provided previously is lost from the datagridview!!
I cant understand why this is happening. anyone please help me. Im totally new to this stuff.. a bit of guidance would be heartily appreciated.
when i had previously used MySQL for the same purpose, the updated data would be permanently stored to the database, but since i migrated from the MySQL to SQL Server's Service Based Database, i get such confusing error.
......
void loadData()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT SNo,Customer_ID, Citizenship_No, Name, Subscription_Date, Phone_No, Location,Locality,Bulbs,Deposit,Monthly_Charge FROM customerinformation;", con);
try
{
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewCustomerInformation.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
try
{
float m_chrg = Convert.ToInt64(textBoxBulbs.Text)*500;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("INSERT INTO customerinformation(SNo,Customer_ID,Citizenship_No,Name,Subscription_Date,Location,Locality,Bulbs,Deposit,Phone_No,Monthly_Charge) values('" + textBoxSNo.Text + "','" + textBoxCustomerID.Text + "','" + textBoxCitizenshipNumber.Text + "','" + textBoxName.Text + "','" + textBoxSubscriptionDate.Text + "','" + textBoxLocation.Text + "','" + textBoxLocality.Text + "','" + textBoxBulbs.Text + "','" + textBoxDeposit.Text + "','" + textBoxPhoneNumber.Text + "','" + m_chrg + "')", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(reader);
con.Close();
dataGridViewCustomerInformation.DataSource = dt;
loadData();
MessageBox.Show("Entry Added!");
fillListbox();
textBoxSNo.Clear();
textBoxBulbs.Clear();
textBoxCitizenshipNumber.Clear();
textBoxCustomerID.Clear();
textBoxDeposit.Clear();
textBoxLocality.Clear();
textBoxLocation.Clear();
textBoxPhoneNumber.Clear();
textBoxName.Clear();
textBoxSubscriptionDate.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If you have your MDF listed in your project files then the property Copy To Output Directory handles how your MDF file is copied to the output directory (BIN\DEBUG or BIN\RELEASE).
If this property is set to Copy Always, then when you run your program a fresh copy of your database file is copied from the project folder to the output effectively destroying every data that you have inserted, modified, deleted in the previous run of your program.
The best solution to this dilemma is to add the MDF file as a permanent database inside your current install of Sql Server and adjust your connection string. And of course set the property to Copy Never
In alternative you could set to Copy if newer. This will allow to change the database schema inside the Server Explorer and let the Visual Studio IDE copy the new structure only after you have made changes.
UPDATE BUT IMPORTANT Not related to your actual question, but your insert query is a serious problem. Do not use string concatenation to build a sql command text. Particularly if the partial text comes from user input. You could face syntax errors (if someone places a single quote inside a text box) or worst, a Sql Injection problem (see here for a funny explanation)
To find good examples of Insert search for 'parametrized query'

File upload control error-Access denied used by another person

when upload the same file for the multiple times i am getting this error......
"The process cannot access the file 'd:\MarketingSystem\ExcelImport\Sample.xls' because it is being used by another process."
getting error in this line
RevenueDumpFileUpload.PostedFile.SaveAs(Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName);
This is my full code.....
protected void btnImport_Click(object sender, EventArgs e)
{
if (RevenueDumpFileUpload.HasFile)
{
string strFilePathOnServer = ConfigurationManager.AppSettings["RevenueDumpFileLocation"];
String sConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName + ";Extended Properties=Excel 8.0;";
string strPostedFileName = RevenueDumpFileUpload.PostedFile.FileName;
if (strPostedFileName != string.Empty && RevenueDumpFileUpload.PostedFile.ContentLength != 0)
{
//Delete Old file before uploading new file.
if (System.IO.File.Exists(strFilePathOnServer))
{
System.IO.File.Delete(strFilePathOnServer);
}
//Save-Upload File to server.
RevenueDumpFileUpload.PostedFile.SaveAs(Server.MapPath(strFilePathOnServer) + RevenueDumpFileUpload.FileName);
RevenueDumpFileUpload.FileContent.Dispose();
}
OleDbConnection Exlcon = new OleDbConnection(sConnectionString);
try
{
Exlcon.Open();
}
catch
{
return;
}
finally
{
RevenueDumpFileUpload.PostedFile.InputStream.Flush();
RevenueDumpFileUpload.PostedFile.InputStream.Close();
}
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", Exlcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1, "XLData");
methodtosave();
}
}
In my web config file:
<appSettings>
<add key="RevenueDumpFileLocation" value="~/ExcelImport/"/>
How to resolve this?
Help me..
Thanks in advance
Well, if the OleDbConnection acts anything like the SqlConnection object, you've got this line:
Exlcon.Open();
which is opening the connection, but you don't have a matching line to close the connection. Which means the Jet database provider is going to continue to keep this file open until the connection object is garbage collected. It would be far better to wrap this line:
OleDbConnection Exlcon = new OleDbConnection(sConnectionString);
In a using statement, whose body extends over the remainder of the function, so that you're guaranteed that it's closed/disposed.
Next, have you considered what happens if multiple users upload files with the same name simultaneously - this method will be broken. It may be better to use a new file name on the server, related to the user ID or session ID, and wrap a try/finally around the whole method to ensure the file is deleted after use.
The above may be the cause of your current issues, if this is an error coming out of production - if two people attempt an upload at the same time, then both of their requests may go past the "delete if it exists" part of the code, then one request manages to save the file and open a connection, then the other request will fall over when trying to save the same file name.
You forget to pass the File Name and File Extension when you are trying to delete the file.
if (System.IO.File.Exists(Server.MapPath(strFilePathOnServer) + strPostedFileName+
System.IO.Path.GetExtension(RevenueDumpFileUpload.FileName)))
{
System.IO.File.Delete(Server.MapPath(strFilePathOnServer) + strPostedFileName +
System.IO.Path.GetExtension(RevenueDumpFileUpload.FileName) );
}

Categories