I have this code here:
public class clsDataLayer
{
// This function saves the personnel data
public static bool SavePersonnel(string Database, string FirstName, string LastName,
string PayRate, string StartDate, string EndDate)
{
bool recordSaved;
try
{
// Retrieving information
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Inserting information into the table
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName, PayRate, StartDate, EndDate) values ('" +
FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate +
"', '" + EndDate + "')";
// Gets the statement to execute at the data source
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Executes the SQL statement and returns the number of rows
command.ExecuteNonQuery();
// Closes the connection to the data source
conn.Close();
recordSaved = true;
}
catch (Exception)
{
recordSaved = false;
}
return recordSaved;
}
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string Database)
{
// States the classes used
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Defines sqlConnclass and what each will consist of
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
// Defines sqlDA and what each will consist of
sqlDA = new OleDbDataAdapter("select * from tblUserActivity", sqlConn);
// Defines DS and what each will consist of
DS = new dsUserActivity();
// Outputs the results from the information gathered
sqlDA.Fill(DS.tblUserActivity);
// Starts over for a new user
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string FormAccessed)
{
// Defines the connection to the database
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
public clsDataLayer()
{
}
public static dsPersonnel GetPersonnel(string p)
{
throw new NotImplementedException();
}
}
I need to add this code but everytime I do I get an error that says No overload for method 'GetPersonnel' takes '1' arguments
// This function gets the user activity from the tblPersonnel
public static dsPersonnel GetPersonnel(string Database, string strSearch)
{
dsPersonnel DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
//create the connection string
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
string query;
if (strSearch == "" || strSearch.Trim().Length == 0)
{
query = "SELECT * from tblPersonnel";
}
else
{
query = "select * from tblPersonnel where LastName = '" + strSearch + "'";
}
// Defines sqlDA and what each will consist of
sqlDA = new OleDbDataAdapter("select * from tblPersonnel", sqlConn);
// Defines DS and what each will consist of
DS = new dsPersonnel();
// Outputs the results from the information gathered
sqlDA.Fill(DS.tblPersonnel);
// Starts over for a new user
return DS;
}
// This function saves the user activity
public static void SavePersonnel(string Database, string FormAccessed)
{
// Defines the connection to the database
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblPersonnel (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
It looks like you're defining
public static dsPersonnel GetPersonnel
twice in the same class. I suspect you are REPLACING the single-arg version with the two-arg version but somewhere you're still calling the single-arg version.
I know you're not asking for this sort of input, but I can't help myself...
You should wrap your OleDbConnections in a using block to make sure they get closed like so:
using (OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database))
{
conn.Open();
...
{
Not sure where your strSearch data is coming from, but you're setting yourself up for a nasty SQL Injection attack with this line:
query = "select * from tblPersonnel where LastName = '" + strSearch + "'";
you should use SQL parameters or a stored procedure.
Related
I am working on a project where I have to upload the excel file in the SQL server database, and also update if the records already exist so far I have implemented the code using SQL bulk cop which is inserting the excel file to the DB table, but I am stuck how to update if the records already available.
I am using asp.net c# for this, this is my code so far, help me and also guide me the best approach of uploading the excel file to the database
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
int id;
string contactPerson;
string designation;
string company;
string contact;
string emailaddress;
string city;
string region;
string industry;
string division;
string mobile;
string address;
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/uploadExcel/") + FileUpload1.FileName);
String ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
// OleDbConnection myconn =
//new OleDbConnection( #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';");
mycon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr[0].ToString() != "")
{
// Response.Write("<br/>"+dr[0].ToString());
id = Convert.ToInt32(dr[0].ToString());
contactPerson = dr[1].ToString();
designation = dr[2].ToString();
company = dr[3].ToString();
emailaddress = dr[4].ToString();
contact = dr[5].ToString();
mobile = dr[6].ToString();
address = dr[7].ToString();
city = dr[8].ToString();
region = dr[9].ToString();
industry = dr[10].ToString();
division = dr[11].ToString();
UpdateDatabase(id, contactPerson, designation, company, emailaddress, contact,
mobile, address,city,region,industry,division);
}
else
{
break;
}
}
lblmessage.Text = "Data Has Been Updated Successfully";
mycon.Close();
File.Delete(ExcelPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//designation, company, emailaddress, contact, mobile, address,city,region,industry,division
private void UpdateDatabase(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address,String city,String region,String industry,
String division)
{
String query = "insert into Tbl_TempExcelData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
//String mycon = "Data Source=Ali-PC\\SQLEXPRESS; Initial Catalog=ExcelDatabase; Integrated Security=True";
String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
Create user-defined type in sql server with all the valves you want to insert
After that user Sql server merge statement to insert and update record in one query.
How to use Sql Merge
in Sql Merge statment use your user defined table variable as source table and the table in which you want to insert use that as target table.
so I have this program which when I press a button inserts a record into an excel spreadsheet with, the columns, being , customer, product, weight, dateTime. Now I want to be able to update a record if the same customer, and product occurs, but I also want to add the previous weight field with the new field, and update the time.
The problem is i'm not sure how to modify my update statement to do this.
// Load data from database, and Update database if filed already exists
DataSet ds = new DataSet();
string insertquery = "SELECT * FROM [Sheet1$] where [Customer] = '" + lblcustomername + " ' ";
OleDbConnection myConnection = new OleDbConnection(OutputDatabaseConnectionString); //define new connection object
OleDbDataAdapter mydataadapter = new OleDbDataAdapter(insertquery, myConnection); //define data adaptor and select column data from spreadsheet
mydataadapter.Fill(ds);
int i = ds.Tables[0].Rows.Count;
// If item exists in database, update it
if (i > 0)
{
try
{
System.Data.OleDb.OleDbConnection myConnection2; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection2 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection2.Open();
myCommand.Connection = myConnection2;
sql = "UPDATE [Sheet1$] SET [Net Weight(Kg)]= '" + textBox1.Text + "' WHERE [Customer] = '" + lblcustomername + "'";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection2.Close();
myConnection2.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// if it doesn't exist update database
try
{
System.Data.OleDb.OleDbConnection myConnection1; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection1 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection1.Open();
myCommand.Connection = myConnection1;
sql = sql = "INSERT INTO [Sheet1$] ([Customer],[Product],[Net Weight(Kg)], [DateTime]) VALUES('" + lblcustomername.Text + "','" + lblproductname.Text + "','" + textBox1.Text + "','" + (DateTime.Now).ToString() + "')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection1.Close();
myConnection1.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I'm supposed to take some code from my professor and add it to the code I have, but I'm experiencing issues with the function I was told to include and I'm not really sure how I can resolve this issue. I've read some of the other questions that were posted already, but I can't really be sure those are the same thing.
ERROR RESOLVED: Were brackets missing and mistyped variables & method flying around (provided by answer below!)
Error 1: Expected class, delegate, enum, interface, or struct
Error 2: Expected class, delegate, enum, interface, or struct
Error 3: Type or namespace definition, or end-of-file expected
Error 4: clsDataLayer' does not contain a definition for 'SavePersonnel'
Error 5: clsDataLayer' does not contain a definition for 'GetPersonnel'
This was supposed to be an add in and move on kind of deal--not sure if it's my code that's the issue or the code supplied. How do I fix this?
Code Provided: Error 1, 2, & 3
// ERROR OCCURS at bool
public static bool SavePersonnel(string Database, string FirstName, string LastName,
string PayRate, string StartDate, string EndDate)
{
bool recordSaved;
try {
// ERROR 2 OCCURS HERE after new !!!!!
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Add your comments here
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName, PayRate, StartDate, EndDate) values ('" +
FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate +
"', '" + EndDate + "')";
// Add your comments here
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
// Add your comments here
conn.Close();
recordSaved = true;
} //<-- ERROR 3 is at this curly bracket
catch (Exception ex) {
recordSaved = false;
}
return recordSaved;
}
Code Provided: Error 4
// ERROR AFTER clsDataLayer.
if (clsDataLayer.SavePersonnel(Server.MapPath("PayrollSystem_DB.accdb"),
Session["txtFirstName"].ToString(),
Session ["txtLastName"].ToString(),
Session ["txtPayRate"].ToString(),
Session ["txtStartDate"].ToString(),
Session ["txtEndDate"].ToString()))
{
txtVerifiedInfo.Text = txtVerifiedInfo.Text +
"\nThe information was successfully saved!";
}
else
{
txtVerifiedInfo.Text = txtVerifiedInfo.Text +
"\nThe information was NOT saved.";
}
Code Provided: Error 5
if (!Page.IsPostBack)
{
//Declare the Dataset
dsPersonnel myDataSet = new dsPersonnel();
//ERROR AFTER clsDataLayer.
myDataSet = clsDataLayer.GetPersonnel(Server.MapPath("PayrollSystem_DB.accdb"));
//Set the DataGrid to the DataSource based on the table
grdViewPersonnel.DataSource = myDataSet.Tables["tblPersonnel"];
//Bind the DataGrid
grdViewPersonnel.DataBind();
Additional Code adding, required for Error 5:
// This function retrieves all data from tblPersonnel table
public static dsPersonnel GetPersonnel (string Database, string strSearch)
{
dsPersonnel DS;
OleDbConnection SqlConn;
OleDbAdapter sqlDA;
//Opens OleDbConnection
sqlConn = new OleDBConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Database);
//Employee Search (procured from video, add in later?
if (strSearch == null || strSearch == "")
{
sqlDA = new OleDbDataAdapter("Select * from tblPersonnel", sqlConn);
}
else
{
sqlDA = new OleDbAdapter("Select '' from tblPersonnel where LastName = '" + strSearch + "'", sqlConn);
}
//Sets Value of DS
DS = new dsPersonnel();
//Fills Table with Data
sqlDA_Fill(DS.tblPersonnel);
//Return value
return DS;
}//End Function: Public static dsPersonnel GetPersonnel
Error 1, 2 & 3
Expected class, delegate, enum, interface, or struct
In C#, methods should always be part of a class.
In your case, you have your method flying around without a parent, so the compiler will complain with this error.
To fix this, define your method inside a class:
// C# class
public class clsDataLayer
{
// This functions insert data into tblPersonnel table
public static bool SavePersonnel(string Database, string FirstName, string LastName, string PayRate, string StartDate, string EndDate)
{
bool recordSaved;
try
{
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Add your comments here
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName, PayRate, StartDate, EndDate) values ('" + FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate + "', '" + EndDate + "')";
// Add your comments here
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
// Add your comments here
conn.Close();
recordSaved = true;
}
catch (Exception ex)
{
recordSaved = false;
}
return recordSaved;
}
// This function retrieves all data from tblPersonnel table
public static dsPersonnel GetPersonnel (string Database, string strSearch)
{
dsPersonnel DS;
OleDbConnection SqlConn;
OleDbAdapter sqlDA;
//Opens OleDbConnection
sqlConn = new OleDBConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Database);
//Employee Search (procured from video, add in later?
if (strSearch == null || strSearch == "")
{
sqlDA = new OleDbDataAdapter("Select * from tblPersonnel", sqlConn);
}
else
{
sqlDA = new OleDbAdapter("Select '' from tblPersonnel where LastName = '" + strSearch + "'", sqlConn);
}
//Sets Value of DS
DS = new dsPersonnel();
//Fills Table with Data
sqlDA_Fill(DS.tblPersonnel);
//Return value
return DS;
}
//End Function: Public static dsPersonnel GetPersonnel
}
Error 4 & 5
clsDataLayer' does not contain a definition for 'SavePersonnel'
This is clearly related to the previous error.
Since SavePersonnel was wrongly declared, the compiler complains it does not exist.
Once we solve errors 1, 2 & 3, the errors 4 & 5 should disappear too.
How Do I Find the ID from the first query and return this value so it can be inserted into query2? This is the code that needs done when a user completes a form on front end. I need to populate two tables and they will relate through the ID "StoryID" which is a primary key that is automatically created.
protected void Upload2_Click(object sender, EventArgs e)
{
userStoryForm.Visible = false;
info.Text = "You have successfully added a new user story.";
String connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
String usernameData = username.Text.ToString();
int captureProjectID = Convert.ToInt32(Request.QueryString.Get("ProjectID"));
String storyno = StoryNoTextBox.Text;
String userstory = StoryTextTextBox.Text;
//Create connection
SqlConnection myConnection = new SqlConnection(connectionString);
//open connection
myConnection.Open();
String query = "INSERT INTO UserStories (StoryNo, StoryText, ProductOwner, ProjectID) " +
"VALUES ('" + storyno + "','" + userstory + "','" + usernameData + "','" + captureProjectID + "')" +
"SELECT SCOPE_IDENTITY() AS StoryID;";
SqlCommand myCommand = new SqlCommand(query, myConnection);
// Call GetOrdinal and assign value to variable.
SqlDataReader reader = myCommand.ExecuteReader();
int StoryIDData = reader.GetOrdinal("StoryID");
// Use variable with GetString inside of loop.
while (reader.Read())
{
Console.WriteLine("StoryID={0}", reader.GetString(StoryIDData));
}
// Call Close when done reading.
reader.Close();
//insert productowner, projectID and storyID into ProductBacklog table
String query2 = "INSERT INTO ProductBacklog (ProductOwner, ProjectID, StoryID) VALUES ('" + usernameData + "', #returnProjectID,'" + StoryIDData + "')";
SqlCommand myCommand2 = new SqlCommand(query2, myConnection);
myCommand2.Parameters.AddWithValue("#returnProjectID", captureProjectID);
//close connection
myConnection.Close();
}
}
Most important - use parameters in your SQL command. Never concatenate strings like that. You're asking for an SQL injection attack.
string query = #"
INSERT INTO UserStories (StoryNo, StoryText, ProductOwner, ProjectID)
VALUES (#storyno, #userstory, #usernameData, #captureProjectID)
SELECT CAST(SCOPE_IDENTITY() AS INT)";
SqlCommand myCommand = new SqlCommand(query);
myCommand.Parameters.Add("#storyno", DbType.String).Value = storyno;
...
To get the returned id, use ExecuteScalar():
int StoryIDData = (int)myCommand.ExecuteScalar();
Also, you don't dispose your resources correctly. If an exception is thrown in the method, the SQLConnection will not be closed. You should put it in a using statement.
I add data from a text to excel with insert into, but it's always show string format. I want it float format(0.2, 1, 20) and I cant change them in excel (for example a coloumn in one time, only it could be changed by one by for all cells). I tried tryparse or converttoint32 func. but nothing change in excel, the numbers are still in text format..
public void ExcelWrite(string date, string station_name, string station_no, string xvaluee)
{
try
{ float j;
xvaluee=xvaluee.Trim();
float.TryParse(Valuee, out j);
string szConn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C://data.xls';Extended Properties='Excel 8.0;HDR=YES'";
OleDbConnection conn = new OleDbConnection(szConn);
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sayfa1$]([Station_No],[Station_Name],[Date],[Valuee]) VALUES('" + station_no + "','" + station_name + "','" + date + "','" + j + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
since you adding '' for each parameter all will take as strings
use Parameters as below
using(OleDbConnection cn = new OleDbConnection(szConn ))
{
cn.Open();
OleDbCommand cmd1 = new OleDbCommand("INSERT INTO [Sayfa1$]([Station_No],[Station_Name],[Date],[Valuee]) VALUES(?,?,?,?)", cn);
cmd1.Parameters.AddWithValue("#p1", station_no );
cmd1.Parameters.AddWithValue("#p2", station_name );
cmd1.Parameters.AddWithValue("#p3",date );
cmd1.Parameters.AddWithValue("#p4", j);
cmd1.ExecuteNonQuery();
}