SQL command INSERT doesn't insert data into table, but debug shows it did (C#) - sql

I can't get what is happening to my app. I'm using a SQL CE (.sdf file) to a local database (winform app) and when I debug, everything runs pretty well, I have in the end of it the message that my data was inserted well. But later on, when I check my databse, its empty.
What should I do?
This is my code:
SqlCeConnection conn = new SqlCeConnection(#"Data Source=|DataDirectory|\Database\Livraria.sdf;");
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO Livros (Codigo, ISBN, Titulo, Editora, Localizacao, Valor, QTD, Autor, AutorEspiritual, Data_)
VALUES (#Codigo, #ISBN, #Titulo, #Editora, #Localizacao, #Valor, #QTD, #Autor, #AutorEspiritual, #Data_)";
cmd.Parameters.AddWithValue("#Codigo", codigo);
cmd.Parameters.AddWithValue("#ISBN", isbn);
cmd.Parameters.AddWithValue("#Titulo", titulo);
cmd.Parameters.AddWithValue("#Editora", editora);
cmd.Parameters.AddWithValue("#Localizacao", localizacao);
cmd.Parameters.AddWithValue("#Valor", valor);
cmd.Parameters.AddWithValue("#QTD", entradas);
cmd.Parameters.AddWithValue("#Autor", autor);
cmd.Parameters.AddWithValue("#AutorEspiritual", autorEspiritual);
cmd.Parameters.AddWithValue("#Data_", data_);
try
{
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Livro adicionado com sucesso!");
}
else
{
MessageBox.Show("O livro não foi adicionado.");
}
// Reset campos
Codigo.Text = "";
Titulo.Text = "";
Editora.SelectedIndex = 0;
Valor.SelectedIndex = 0;
Localizacao.SelectedIndex = 0;
Entrada.Text = "";
Isbn.Text = "";
Autor.SelectedIndex = 0;
AutorEspiritual.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}

You have two databases. You are inserting to one and looking for the results in another.
Or, you are starting a transaction, inserting but then not committing.

The first thing you need to do is to create a simple select statement first that gets record from you sqlce database.
if( has record//connected )
{
//Proceed to your insert statement remove if else and use
conn.Open();
cmd.ExecuteNonQuery()
//then check your DB again
}
else
{
//Problem on you connection string
}
Your sqlce database is located on your bin folder
Regards

Related

Show value from database with dataset in a label

I would like to show database value in a label.
Now it pops up in a MessageBox with the value, but I don't need a MessageBox.
private void HandleSelect()
{
string connection =
"Server = DESKTOP-IRAEU36; Database = Test; Trusted_Connection = True;";
string sql = txtSql.Text;
try
{
SqlDataAdapter adapterSql = new SqlDataAdapter(sql, connection);
DataSet data = new DataSet();
adapterSql.Fill(data);
//dataSQL.DataSource = data.Tables[0];
for (int i = 0; i < data.Tables[0].Rows.Count; i++)
{
// This is working:
MessageBox.Show(data.Tables[0].Rows[1][1].ToString());
// This is not working:
lbl1.Text.Show(data.Tables[0].Rows[1][1].ToString());
}
}
catch (Exception ex)
{
labAusgabe.Text = ex.Message;
}
}
Change your code to this:
lbl1.Text = data.Tables[0].Rows[1][1].ToString();

ASP.Net MVC Passing array value to database table columns

I used the code from http://arranmaclean.wordpress.com/2010/07/20/net-mvc-upload-a-csv-file-to-database-with-bulk-upload/#comment-188 to upload, read and insert to DB the csv file. My problem now is how can I pass the values from the csv file to the specific database table columns.
string Feedback = string.Empty;
string line = string.Empty;
string[] strArray;
DataTable dt = new DataTable();
DataRow row;
Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
StreamReader sr = new StreamReader(fileName);
line = sr.ReadLine();
strArray = r.Split(line);
Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn()));
while ((line = sr.ReadLine()) != null)
{
row = dt.NewRow();
row.ItemArray = r.Split(line);
dt.Rows.Add(row);
}
and ...
private static String ProcessBulkCopy(DataTable dt)
{
string Feedback = string.Empty;
string connString = ConfigurationManager.ConnectionStrings["DataBaseConnectionString"].ConnectionString;
using( SqlConnection conn = new SqlConnection(connString))
{
using (var copy = new SqlBulkCopy(conn))
{
conn.Open();
copy.DestinationTableName = "BulkImportDetails";
copy.BatchSize = dt.Rows.Count;
try
{
copy.WriteToServer(dt);
Feedback = "Upload complete";
}
catch (Exception ex)
{
Feedback = ex.Message;
}
}
}
return Feedback;
}
Below are my sample contents:
08/01/12,05:20:12 AM,243752,,South Lobby3,522557,IN
08/01/12,05:26:03 AM,188816,,North Lobby1,358711,IN
My DB table columns:
empno | date | time
I only need to insert the first three arrays.. (e.g. 08/01/12,05:20:12 AM,243752) and proceed to the next row to insert it again to its specified columns. My csv file doesn't have headers. I saw a code about passing the array values but it requires headers. How can I pass the values even without having a header in my csv file? Please help me guys.. Thank you..

Using C# remove unnecessary “TABLE_NAME” from Excel worksheets

Can anyone tell me, I am going to upload excel file, this file has unnecessary table like "_xlnm#Print_Titles" that I need to remove or delete that field. This a my method. But it is does not work for remove or delete.
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if ((dt == null) )
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
if ((excelSheetNames[i].Contains("_xlnm#Print_Titles") || (excelSheetNames[i].Contains("Print_Titles"))))
{
if (true)
{
row.Table.Rows.Remove(row);
dt.AcceptChanges();
}
}
i++;
}
return excelSheetNames;
}
Instead of removing items in the foreach loop, we'll find them and add them to a list, then we'll go through that list and remove them from your data table.
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if ((dt == null))
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
var rowsToRemove = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
var row = dt.Rows[i];
excelSheetNames[i] = row["TABLE_NAME"].ToString();
if ((excelSheetNames[i].Contains("_xlnm#Print_Titles") || (excelSheetNames[i].Contains("Print_Titles"))))
{
rowsToRemove.Add(dt.Rows[i]);
}
i++;
}
foreach (var dataRow in rowsToRemove)
{
dt.Rows.Remove(dataRow);
}
return excelSheetNames;
}
Those _xlnm and "$" are sheets that, turns out, shouldn't be normally accessed by the users.
You can solve this in 2 ways.
Ignore them
Drop them
The former is highly recommended.
To do this you need to use the following code:
if (!dt.Rows[i]["Table_Name"].ToString().Contains("FilterDatabase") && !dt.Rows[i]["Table_Name"].ToString().EndsWith("$'"))
{
}
You can either use .Contains() and/or .EndsWith() to filter out those sheets.

Oracle columns update not happpening

I am trying to update a few columns in a Oracle table from my C# code.
Here is my method:
private static bool UpdateOracleTable(OracleTable table, string whereClause, List<int> entIDs)
{
try
{
var tableName = table.ToString();
using (OracleConnection conn = new OracleConnection(_oracleConnection))
{
conn.Open();
foreach (var id in entIDs)
{
whereClause = String.Format(whereClause, id);
var query = Resources.UpdateOracle;
query = String.Format(query, tableName, "20", DateTime.Now.ToString("yyyy/MM/dd"), whereClause);
using (OracleCommand cmd = new OracleCommand(query, conn))
{
cmd.ExecuteNonQuery();
}
}
}
return true;
}
catch (Exception ex)
{
Log.Debug(LogType.Error, ex);
return false;
}
}
Here is the Query:
UPDATE
{0}
SET
SYNC_STATUS = '{1}'
,SYNC_DATE = TO_DATE('{2}', 'yyyy/mm/dd')
{3}
And the where clause will look something like:
WHERE ID = {0}
This method updates about 10 records, and the rest stays null. This mehod does return true, and I have debugged, no exception is thrown.
Why does it not update all records?
This isn't an answer but might help debug the problem.
Instead of the like:
cmd.ExecuteNonQuery();
put in this:
int count = cmd.ExecuteNonQuery();
if (count == 0)
{
Console.WriteLine("");
}
Put a break on the Console.WriteLine("") and run it. The debugger will stop if no rows were updated. You can then check the query, and whether or not that ID actually exists.
The problem was with the WHERE clause. Since it contains a place holder {0}, after I I formatted the WHERE clause, the ID always stayed to the value it was formatted with first.
This is what my new method looks like.
private static bool UpdateOracleTable(OracleTable table, string whereClause, List<int> entIDs)
{
try
{
var tableName = table.ToString();
using (OracleConnection conn = new OracleConnection(_oracleConnection))
{
conn.Open();
foreach (var id in entIDs)
{
string originalWhere = whereClause;
originalWhere = String.Format(originalWhere, id);
var query = Resources.UpdateOracle;
query = String.Format(query, tableName, "20", DateTime.Now.ToString("yyyy/MM/dd"), originalWhere);
using (OracleCommand cmd = new OracleCommand(query, conn))
{
bool success = cmd.ExecuteNonQuery() > 0;
}
}
}
return true;
}
catch (Exception ex)
{
Log.Debug(LogType.Error, ex);
return false;
}
}
As can be seen, I added a variable 'originalWhere', that gets formatted, but most importantly, is being set to original WHERE clause parameter passed, so that it will always contain the place holder.

Sending parameters to a stored procedure

Where is the problem in my code?
I use a stored procedure and transaction.
For one parameter to be working properly, but when the number of parameters is more than one error occurs.
Where is my problem?
This is my code in C#
internal static bool ExecuteNonQueryTransaction(string CommandName, CommandType cmdType, SqlParameter[][] pars)
{
int result = 0;
SqlTransaction tr = null;
int h = pars.GetLength(0);
using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
tr = con.BeginTransaction();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.Transaction = tr;
cmd.CommandText = CommandName;
// cmd.Parameters.AddRange(pars);
for (int i = 0; i < pars.GetLength(0); i++)
{
cmd.Parameters.AddRange(pars[i]);
cmd.ExecuteNonQuery();
}
tr.Commit();
}
}
catch
{
if (tr != null)
{
tr.Rollback();
}
//return false;
}
}
return (result > 0);
}
and this my stored procedure
ALTER PROCEDURE dbo.AddNewUserTypePageAccess
(#id_user_type int,
#id_page_access int)
as
insert into user_type_page_access(id_user_type, id_page_access)
values(#id_user_type, #id_page_access)
return
Thank you for your help.....
You shouldn't call ExecuteNonQuery(); inside the loop that adds the parameters! Add all parameters, and then call ExecuteNonQuery(); once, with all the parameters in place.
Use this code:
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.Transaction = tr;
cmd.CommandText = CommandName;
// cmd.Parameters.AddRange(pars);
for (int i = 0; i < pars.GetLength(0); i++)
{
cmd.Parameters.AddRange(pars[i]);
}
// call ExecuteNonQuery only AFTER you've added all the parameters!
cmd.ExecuteNonQuery();
tr.Commit();
}