Error in ado.net crud operations - c#

I want to update details. I have code in a data access class. But after executing ExecuteScalar(), it goes to the catch block and shows an exception as null.
Program :
public bool UpdateData(Customer objcust) // passing model class object because it contains all customer properties.
{
SqlConnection con = null;
// string result = "";
//int rows = 0;
try
{
string connectionString = #"server=(local)\SQLExpress;database=CustDemo;integrated Security=SSPI;";
con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE Customer SET Name = #Name , Address = #Address, Gender =#Gender , City=#City WHERE Customer.CustomerID = #CustomerID",con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", objcust.Name);
cmd.Parameters.AddWithValue("#Gender", objcust.Gender);
cmd.Parameters.AddWithValue("#Address", objcust.Address);
cmd.Parameters.AddWithValue("#City", objcust.City);
con.Open();
cmd.ExecuteScalar();
return true;
}
catch(Exception ex)
{
return false;
}
}

Instead of cmd.ExecuteScalar(); Try to use
cmd.ExecuteNonQuery ();
ExecuteNonQuery is used specifically executing UPDATE, INSERT, or DELETE statements.

Related

How can you retrieve the value of sys_guid() after an OracleCommand INSERT INTO

I want to retrieve the value of a certain column that contain an Oracle db generated sys_guid() within a transaction.
public string GetGUID(OracleConnection connection)
{
string guid = "";
connection.Open();
OracleCommand cmd = new OracleCommand();
OracleTransaction transaction;
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = transaction;
cmd.Connection = connection;
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO CUSTOMERS (NAME,DETAILS) VALUES (:nm, :dts)";
cmd.Parameters.Add("nm", OracleDbType.VarChar);
cmd.Parameters["nm"].Value = name;
cmd.Parameters.Add("dts", OracleDbType.VarChar);
cmd.Parameters["dts"].Value = details;
cmd.Prepare();
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
}
reader.Close();
transaction.Commit();
}
catch (Exception e)
{
transaction.Rollback();
Console.WriteLine(e.Message);
}
return guid;
}
Table CUSTOMERS have a column ORDER that creates a guid with SYS_GUID(), how can I retrieve that guid?
try returning .. into clause e.g.
...
using (OracleCommand cmd = connection.CreateCommand()) {
cmd.CommandText =
#"INSERT INTO CUSTOMERS (
NAME,
DETAILS)
VALUES (
:nm,
:dts)
RETURNING
""ORDER"" INTO :orderid";
cmd.Parameters.Add("nm", OracleDbType.VarChar);
cmd.Parameters["nm"].Value = name;
cmd.Parameters.Add("dts", OracleDbType.VarChar);
cmd.Parameters["dts"].Value = details;
cmd.Parameters.Add("orderid", OracleDbType.VarChar);
cmd.Parameters["orderid"].Direction = ParameterDirection.Output;
try {
cmd.ExecuteNonQuery(); // Just execute, nothing to read
transaction.Commit();
guid = Convert.ToString(cmd.Parameters["orderid"].Value);
}
catch (Exception e) { //TODO: put more specific exception type
transaction.Rollback();
Console.WriteLine(e.Message);
}
return guid;
}
...

Display into textbox using if sentence

I'm displaying some data from the database into textboxes on my windows form and I have to add something else but it depends on the account type (that information is saved on my Databse). Meaning it is either DM (domestic) or CM(comercial). I want for it to charge an extra amount if it's CM.
I would appreciate any help, thank you.
OracleDataReader myReader = null;
OracleCommand myCommand = new OracleCommand("SELECT SUM(IMPORTE) AS corriente FROM MOVIMIENTOS WHERE CUENTA='"+txtIngreseCuenta3.Text + "'AND CONCEPTO=10", connectionString);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtCorriente.Text = (myReader["corriente"].ToString());
}
I'm using this code to display into the textbox but I want it to get the account type from another table and IF it's CM then add a certain amount into a textbox.
In your case I suggest that you use Execute Scalar instead of reader since you are returning only one value from the database. but in your case if you want this code to work you need to Cast the returned value into the correct dot net type and then populate the TextBox.
Example Using ExecuteReader
//txtCorriente.Text = ((int)myReader["corriente"]).ToString();
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtCorriente.Text = ((int)reader["corriente"]).ToString();
txtAnother.Text = ((decimal)reader["another"]).ToString();
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Example Using ExecuteScalar
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}

Connect to SQL Server in C#

I'm a beginner programmer with C#. I'm trying to develop an application that it connects to a database and do the typical operations like insert, delete, update and get.
I'm getting a error with the database connection. I'm working with SQL Server 2012, where I have create a database called company.
This is my code:
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
What is the error? I get an exception on this line:
command.Connection.Open();
Thanks in advance
SqlConnection con = new SqlConnection("Your Connection String Goes here");
You should assign connection to SqlCommand object like this
SqlCommand command = new SqlCommand();
command.Connection = con;
or
SqlCommand command = new SqlCommand("YourQuery",con);
Some Important Steps to Execute Command
1: Create SqlConnection Object and Assign a connection string to that object
SqlConnection con = new SqlConnection("Your Connection String Goes here");
or
SqlConnection con = new SqlConnection();
con.Connection = "Your Connection String Goes here";
2: Create SqlCommand Object and assing a command Text(Your Query) and connection string to that object
SqlCommand command = new SqlCommand("Select * from Products",con);
or
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText ="Select * from Products";
You can also specify CommandType
command.CommandType =CommandType.Text;
/* if you are executing storedprocedure CommandType Will be
=> CommandType.StoredProcedure; */
then You can Execute Command Like this
try
{
con.Open();
int TotalRowsAffected = command.ExecuteNonQuery();
}
catch(Exeception ex)
{
MessageBox.Show(ex.Message);
}
finaly
{
con.Close();
}
Just an FYI: An alternative to the try finally blocks, which ensure the database connection gets closed is to use the using statement such as:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
try
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (InvalidOperationException)
{
//log and/or rethrow or ignore
}
catch (SqlException)
{
//log and/or rethrow or ignore
}
catch (ArgumentException)
{
//log and/or rethrow or ignore
}
}
Refer to the MSDN documentation for the SqlCommand class here, https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx, and look up the ExecuteNonQuery() method, which is used to execute INSERT, UPDATE, and DELETE statements. Then look up ExecuteScalar() method that you can use to execute SELECT statements that return a single value. You can use ExecuteReader() to return a SqlDataReader for SELECT statements that return multiple columns.
not initialize sqlcommand connections, way for initialize this is :
command.Connection=con;
this is complete code for you :
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection=con;
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}

How to add column and description and column type to sql server using c#

I have a list of fields with descriptions and types that needs to be added to a table.
Eg. SomeField/SomeDescription/Decimal
How would I go about adding this columns with descrption and type to a sql server 2012 db using c#? I know how to add the column via sql, but I need to be able to do it in c#
Heres the solution I came up with.
Basically I added the columns using sql (i.e. Alter table etc...)
Then I called an existing sql stored procedure: sp_addextendedproperty
string[] allLines = File.ReadAllLines(#"C:\Table.csv");
var query = from line in allLines
let data = line.Split(',')
select new
{
FieldName = data[0],
Description = data[1]
};
try
{
string connection = "my connection string";
using (SqlConnection conn = new SqlConnection(connection))///add your connection string
{
SqlCommand command = new SqlCommand();
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
command.Connection = conn;
command.Transaction = trans;
foreach (var item in query)
{
String sql = string.Format("ALTER TABLE MyTable ADD {0} Decimal(18,6)", item.FieldName.ToString());
command.CommandText = sql;
command.ExecuteNonQuery();
}
trans.Commit();
}
conn.Close();
conn.Open();
SqlTransaction transaction = conn.BeginTransaction();
using (SqlCommand cmd = new SqlCommand("sp_addextendedproperty", conn, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var item in query)
{
cmd.Parameters.Clear();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = "MS_Description";
cmd.Parameters.Add("#value", SqlDbType.VarChar).Value = item.Description.ToString();
cmd.Parameters.Add("#level0type", SqlDbType.VarChar).Value = "SCHEMA";
cmd.Parameters.Add("#level0name", SqlDbType.VarChar).Value = "dbo";
cmd.Parameters.Add("#level1type", SqlDbType.VarChar).Value = "TABLE";
cmd.Parameters.Add("#level1name", SqlDbType.VarChar).Value = MyTable;
cmd.Parameters.Add("#level2type", SqlDbType.VarChar).Value = "COLUMN";
cmd.Parameters.Add("#level2name", SqlDbType.VarChar).Value = item.FieldName.ToString();
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Something like that:
string connection = "your connection string";
try
{
using(SqlConnection conn = new SqlConnection(connection))///add your connection string
{
String sql="ALter Table MyTable add SomeField Decimal(18,3)";
conn.Open();
using( SqlCommand command = new SqlCommand(sql,conn))
{
command.ExecuteNonQuery();
}
}
}
catch (Ecxeption ex)
{
MessageBox.Show(ex.Message);
}

Transactions in C#

In addition to this question: Preorder tree traversal copy folder
I was wondering if it is possible to create a transaction that contains different calls to the database.
ex:
public bool CopyNode(int nodeId, int parentNode)
{
// Begin transaction.
try
{
Method1(nodeId);
Method2(nodeId, parentNode);
Method3(nodeId);
}
catch (System.Exception ex)
{
//rollback all the methods
}
}
I don't know if this is possible. We are using subsonic to do the database calls.
This is really important, not only for the tree traversal problem but also for some other stuff we do.
The main idea is that we can't let our dabase get corrupted with uncomplete data.
That is possible, you can find a example here
Or perhaps a transaction scope...
http://msdn.microsoft.com/en-us/library/ms172152.aspx
BeginTransaction is called off a ADO.NET collection object.
The Command object needs this transaction (SqlTransaction object) assigned to it.
Commit and Rollback are only called in the outer method.
Check out this code. It works by re-using the SqlConnection and SqlTransaction objects. This is a classic Master>Details type of set up. The master type is ColumnHeaderSet which contains a property of
List<ColumnHeader>
, which is the details (collection).
Hope this helps.
-JM
public static int SaveColumnHeaderSet(ColumnHeaderSet set)
//save a ColumnHeaderSet
{
string sp = ColumnSP.usp_ColumnSet_C.ToString(); //name of sp we're using
SqlCommand cmd = null;
SqlTransaction trans = null;
SqlConnection conn = null;
try
{
conn = SavedRptDAL.GetSavedRptConn(); //get conn for the app's connString
cmd = new SqlCommand(sp, conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
trans = conn.BeginTransaction();
cmd.Transaction = trans; // Includes this cmd as part of the trans
//parameters
cmd.Parameters.AddWithValue("#ColSetName", set.ColSetName);
cmd.Parameters.AddWithValue("#DefaultSet", 0);
cmd.Parameters.AddWithValue("#ID_Author", set.Author.UserID);
cmd.Parameters.AddWithValue("#IsAnonymous", set.IsAnonymous);
cmd.Parameters.AddWithValue("#ClientNum", set.Author.ClientNum);
cmd.Parameters.AddWithValue("#ShareLevel", set.ShareLevel);
cmd.Parameters.AddWithValue("#ID_Type", set.Type);
//add output parameter - to return new record identity
SqlParameter prm = new SqlParameter();
prm.ParameterName = "#ID_ColSet";
prm.SqlDbType = SqlDbType.Int;
prm.Direction = ParameterDirection.Output;
cmd.Parameters.Add(prm);
cmd.ExecuteNonQuery();
int i = Int32.Parse(cmd.Parameters["#ID_ColSet"].Value.ToString());
if (i == 0) throw new Exception("Failed to save ColumnHeaderSet");
set.ColSetID = i; //update the object
//save the ColumnHeaderList (SetDetail)
if (ColumnHeader_Data.SaveColumnHeaderList(set, conn, trans)==false) throw new Exception("Failed to save ColumnHeaderList");
trans.Commit();
// return ID for new ColHdrSet
return i;
}
catch (Exception e){
trans.Rollback();
throw e;
}
finally{
conn.Close();
}
}
public static bool SaveColumnHeaderList(ColumnHeaderSet set, SqlConnection conn, SqlTransaction trans)
//save a (custom)ColHeaderList for a Named ColumnHeaderSet
{
// we're going to accept a SqlTransaction to maintain transactional integrity
string sp = ColumnSP.usp_ColumnList_C.ToString(); //name of sp we're using
SqlCommand cmd = null;
try
{
cmd = new SqlCommand(sp, conn); // re-using the same conection object
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = trans; // includes the cmd in the transaction
//build params collection (input)
cmd.Parameters.Add("#ID_ColSet", SqlDbType.Int);
cmd.Parameters.Add("#ID_ColHeader", SqlDbType.Int);
cmd.Parameters.Add("#Selected", SqlDbType.Bit);
cmd.Parameters.Add("#Position", SqlDbType.Int);
//add output parameter - to return new record identity
//FYI - #return_value = #ID_SavedRpt
SqlParameter prm = new SqlParameter();
prm.ParameterName = "#ID";
prm.SqlDbType = SqlDbType.Int;
prm.Direction = ParameterDirection.Output;
cmd.Parameters.Add(prm);
//Loop
foreach (ColumnHeader item in set.ColHeaderList)
{
//set param values
cmd.Parameters["#ID_ColSet"].Value = set.ColSetID;
cmd.Parameters["#ID_ColHeader"].Value = item.ColHeaderID;
cmd.Parameters["#Selected"].Value = item.Selected;
cmd.Parameters["#Position"].Value = item.Position;
cmd.ExecuteNonQuery();
int i = Int32.Parse(cmd.Parameters["#ID"].Value.ToString());
if (i == 0) throw new Exception("Failed to save ColumnHeaderSet");
}
return true;
}
catch (Exception e)
{
throw e;
}
}

Categories

Resources