The INSERT INTO statement contains the following unknown field name: 'a'. Make sure you have typed the name correctly, and try the operation again - oledb

// e,g, I want to insert 3 columns in 1st row and 10 columns in rest of the rows
//I am Creating excel file with sheet name as MySheet
// then updating value in 1st row, 1st cell of header as blank
//then inserting data
// Can anyone please help to insert data in excel without header
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
";Mode=ReadWrite;Extended Properties=\"Excel 12.0 XML;HDR=NO\"";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "CREATE TABLE [MySheet] (a string)";
cmd.ExecuteNonQuery();
cmd.CommandText = "UPDATE [MySheet$] SET F1 = \"\"";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO [MySheet] (a) values ('ABC')" //<-----Getting error to insert
cmd.ExecuteNonQuery();
}
}
conn.Close();

Just try [removed the (a)]
cmd.CommandText = "INSERT INTO [MySheet] values ('ABC')";

I get the same error. There was a padded space ending column name in Excel. Removing that space from end of column name fixed the issue.

Related

Asp.net Transaction with foreach loop

I am trying to save one Gridview with two checkbox in database with Asp.net Transaction , I am Getting Error when same condition come
SqlCommand cmd = new SqlCommand("procedure", con);
SqlCommand cmd1 = new SqlCommand("procedure1", con);
foreach (GridViewRow row in gvrecept.Rows)
{
if (cash.Checked){
cmd.Parameters.AddWithValue("#parameter", "value");
cmd.Transaction = trns;
}
else if (cheque.Checked)
{
cmd1.Parameters.AddWithValue("#parameter1", "value1");
cmd1.Transaction = trns;
}
}
int i = cmd1.ExecuteNonQuery();
int j = cmd.ExecuteNonQuery();
if (i > 0 && j > 0 )
{
trns.Commit();
}
As explained in my comment above you need to change something:
The trns should be added outside the loop just one time together with the setting to CommandType = CommandType.StoredProcedure and the creation of the two commands.
Inside the loop you should execute the command at each loop for each row you traverse. Also it is not clear if the two commands are mutually exclusive. I mean, if you have two checkboxes set then you should execute both commands but not if you don't have the matching checkbox set. If this is the case you need to use two separate ifs not an else if.
Notice that inside the loop you can simply change the value of the parameter before executing the command. This will be a smaller optimization but nevertheless it is simpler than creating the command or clearing the parameter collection at each loop.
Finally the commit of the Transaction should be done outside the loop when you have completed the insertion. If you have an error then an exception occurs and the Commit is skipped.
Final note. It is not clear why you need two commands at all. In the code above you use always the same StoredProcedure but passing different values. If this is the case then one command will do just fine.
SqlCommand cmd = new SqlCommand("procedure1", con);
cmd.Transaction = trns;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#parameter", SqlDbType.NVarChar);
SqlCommand cmd1 = new SqlCommand("procedure1", con);
cmd1.Transaction = trns;
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#parameter1", SqlDbType.NVarChar);
foreach (GridViewRow row in gvrecept.Rows)
{
if (cash.Checked)
{
cmd.Parameters["#parameter"].Value = "value";
cmd.ExecuteNonQuery();
}
if (cheque.Checked)
{
cmd.Parameters["#parameter1"].Value = "value1";
cmd1.ExecuteNonQuery();
}
}
trns.Commit();

vb.net OLEDB Parametarize query

When i put parameter in my OLEDB code it compile successfully but it doesn't do the task. For example this delete data code:
Try
If dbconn.State = ConnectionState.Closed Then
dbconn.Open()
End
Dim dbCommand As OleDbCommand = New OleDbCommand
dbCommand.CommandText = "DELETE FROM UsersTB WHERE First_Name =?"
dbCommand.Connection = dbconn
dbCommand.Parameters.AddWithValue("#row", 0)
Dim rows = dgvusers.SelectedRows
For Each row In rows
dbCommand.Parameters("#row").Value = row.Cells("First_Name").Value
dbCommand.Connection = dbconn
dbCommand.ExecuteNonQuery()
Next
MsgBox("Deleted")
Catch ex As Exception
ex.ToString()
End Try
This code is written on button when i compiled and click the button it doesn't delete the data i tried putting it on try catch and putting msgbox to indicate if the command is successful it and it indicate its "Deleted" but it doesn't work.

Getting a value from one table to pull up values from another table

I am trying to lookup an employeeid from one table based on the windows login name, and use this employeeid to get values from another table to add them up. So, for Bill, the employeeid is 1 in tblEmployees. I sum all noofhours in tblTimeAvailable where employeeid equals 1 and display this on my webpage. It's not working. I can't figure out how to search the second table by the employeeid found in the first table. (I'm rewriting code because of sql injection.)
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
Dim Connection As String = "Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI"
Using con As New SqlConnection(Connection)
Dim sqlemp As String = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
Dim command As New SqlCommand(sqlemp, con)
con.Open()
rve = cmde.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
End Using
When I look at value of rve, it's giving me #loginname and not the employeeid. FYI - there will always be only one row in tblEmployees because each Windows login name is unique.
'Get Sick Time
Using con As New SqlConnection(Connection)
Dim sqls1 As String = "Select SUM(NoofHours) as Total from tblTimeAvailable where workcode = 1 and EmployeeID = #employeeid"
Dim command As New SqlCommand(sqls1, con)
con.Open()
rvsa = cmde.Parameters.Add(New SqlParameter With {.ParameterName = "#employeeid", .SqlDbType = SqlDbType.NVarChar, .Value = rve})
End Using
' If the sum equals 0, show 0 on webpage. If another value, show value.
If IsDBNull(rvsa) Then
rvsa = 0
TextBoxsa.Text = 0
Else
TextBoxsa.Text = rvsa.ToString
End If
I appreciate any help you can give me!
You are never executing the command. After setting the values of the various parameters, you need to then call one of the execute methods on the SqlCommand object. In this case, since you are just reading a single value from a single row, you can simply use the ExecuteScalar method:
rve = command.ExecuteScalar()

Getting Uncommitted Transactions Sqlite With System.Data.Sqlite

I am trying to get a count of uncommitted records in a SQLite database using the System.Data.Sqlite library. My research thus far has pointed towards using the PRAGMA read_committed, but I always get a count of 0 until records are committed. Any tips?
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + this.Path))
{
conn.Open();
using (SQLiteCommand cmd = new SQLiteCommand(conn))
{
cmd.CommandText = "PRAGMA read_uncommitted = true;";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT Count() FROM Tiles WHERE TileLayerId = " + tileLayerId;
return Convert.ToInt32(cmd.ExecuteScalar());
}
}

Subsonic 3: Strongly typed return value for stored procedures that return mixed results from different tables

Say I have a stored procedure that returns dataSet from 2 different tables. Example:
SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer
FROM Customers LEFT JOIN Sales
ON Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName
Is there any way to get a strongly typed list as a result from this stored procedure ? Something like this:
StoredProcedure sp = myDevDB.GetCustomerSales();
List<MyCustomType> resultSet = sp.ExecuteTypedList<MyCustomType>();
How and where do I define the MyCustomType class ? How do I map its properties to the actual table columns ?
Thanks,
Zohrab.
I just created a asp.net web page that does this. Try this:
DataSet ds = new DataSet();
SqlDataAdapter adtp = new SqlDataAdapter(command);
adtp.Fill(ds);
StringBuilder b = new StringBuilder();
b.AppendLine("class " + this.txtSP.Text + "_QueryResult");
b.AppendLine("{");
foreach ( DataColumn c in ds.Tables[0].Columns )
{
b.AppendLine(string.Format("property {0} {1} {{ get; set; }}", c.DataType, c.ColumnName));
}
b.AppendLine("}" + Environment.NewLine);
this.txtResult.Text = b.ToString();
}
catch { }

Resources