How do I cast decimal values to string from my database? - sql

The below code snippet pulls a pack size column from my table but am using getString which I get an error then now see is an issue because the column am pulling is of decimal type. How would I cast my snippet to accept the decimal values?
try
{
string connectionString = "Data Source=CMDLAP121\\SQLEXPRESS;Initial Catalog=TESTBAR;Integrated Security=True";
string query = "SELECT * FROM BCODEREF WHERE BAR_CODE = '" + comboBox1.Text + "';";
string mystring = query;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string spo = dr.GetString(dr.GetOrdinal("PACKSIZE"));
ponum.Text = spo;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

Parse to decimal first and convert to a string with the format you need:
decimal packSize= 0;
decimal.TryParse(dr["PACKSIZE"].ToString(), out packSize);
ponum.Text = packSize.ToString("0.00"); //specify format you need
See this post for details of how to set up appropriate string format

Related

System.Data.SqlClient.SqlException: Incorrect syntax near "="

I try am trying to build a function that populates a table when given the name of the table and what parameter to order it by.
I think I am just making a syntax error in my SQL command but I can't find it. Please help.
public DataTable populateTable(string tableName, string orderByParameter)
{
DataTable table = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string cmdString = "SELECT * FROM (value = #tbl) ORDER BY (parameter = #obp) DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = cmdString;
cmd.Parameters.AddWithValue("#tbl", tableName);
cmd.Parameters.AddWithValue("#obp", orderByParameter);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
try
{
GridView1.DataSource = table;
GridView1.DataBind();
return table;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
You can't have variables in table name or in 'order by' clause.
You could build the query dynamically as:
string cmdString = "SELECT * FROM [" + tableName + "] ORDER BY " + orderByParameter +" DESC";
With this you won't need to add the parameters #tbl and #obp to the command.
Note that this runs into SQL injection related vulnerabilities. So you shouldn't do this unless you are absolutely certain that the table with given name exists, and the orderByParameter is a valid expression.

SQL Count from specific Column in Database

I want to get a SQL Count of the number of records that pertain to my bundnum column and display it into my textblock. Any suggestions?
SqlConnection conn = new SqlConnection("db connection");
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = 'values' ";
conn.Open();
int returnValue = (int)comm.ExecuteScalar();
txtNumber.Text = returnValue.ToString();
Using Google, I found this helpful link and after some modification:
Int32 newCount = 0;
string newValue = "something";
string sql =
"SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = '#myValue'";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#myValue", SqlDbType.VarChar);
cmd.Parameters["#myValue"].Value = newValue;
try
{
conn.Open();
newCount = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Adding new data error

When i'm running this code, it says:
String or binary data would be truncated. The statement has been
terminated.
On the underlined area, can some one help me with this.
namespace ASP_05
{
public partial class AddEmployee : System.Web.UI.Page
{
public DataSet getDataset(string query)
{
String sConn = "Data Source=(local);Initial Catalog=medewerkers;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(sConn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(query, conn);
da.Fill(ds);
da.Dispose();
return ds;
}
protected void toevoegen_Click(object sender, EventArgs e)
{
String vn = voornaam.ToString();
String an = voornaam.ToString();
String a = voornaam.ToString();
String t = voornaam.ToString();
string query = "INSERT INTO tblMedewerkers (voornaam, achternaam, afdeling, toestelnummer) VALUES ('" + vn + "','" + an + "','" + a + "','" + t + "')";
this.execSQL(query);
}
public int execSQL(string query)
{
String sConn = "Data Source=(local);Initial Catalog=medewerkers;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(sConn);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
}
}
The data that you are inserting in the table for a particular column is more in size than what you have defined in the table. Hence you are getting this error. Go through your column definitions and also through the records you are inserting and check if any of the column have less size than data you are inserting

Send data from one data table to other

I am trying to send data from sql to oracle using bulk copy.
Here is the code
string sqldb = "server=DOR-SQLTEST\\DORSQLSERVER;" + "initial catalog=RD2KTEST;" + "user id=amehra;" + "password=Research#322";
SqlConnection sqlconn = new SqlConnection(sqldb);
sqlconn.Open();
string sqlstring="select TOP 10 POSITION_ID, POSITION_DESC from T_CD_POSITION";
SqlCommand scmd = new SqlCommand(sqlstring, sqlconn);
SqlDataReader reader = scmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine("entered to write to oracle.......\n\n");
string oradb = "Data Source=UHAMPTST;user id=ocg_de;password=rd2k";
OracleConnection oraconn = new OracleConnection(oradb);
oraconn.Open();
Console.WriteLine("orca conn established....");
using( OracleBulkCopy orca_bulk_copy = new OracleBulkCopy(oraconn))
{
orca_bulk_copy.DestinationTableName = "t_test_postion";
orca_bulk_copy.WriteToServer(reader);//line 38
orca_bulk_copy.Close();
orca_bulk_copy.Dispose();
}
}
}
}
}
I'm getting error at line 38 as Oracle Exception occurred.
Kindly rectify the problem

SqlCommand.ExecuteScalar - specify a particular data item

I have a Stored Procedure which returns 10 columns of data. Using cmd.ExecuteScalar() returns the value of the 1st column from the 1st record.
How can I change this so that I can return different columns, by specifying their alias/dataitem name?
I want to be able to do something like:
Dim FirstName as String = cmd.ExecuteScalar("FirstName")
You could create a method that calls ExecuteReader, and then uses GetOrdinal with your column name to then call GetString.
My VB is non-existent, but this is the C# for an extension method.
public static class SqlCommandExt
{
public static string ExecuteScalar(this SqlCommand cmd, string columnName)
{
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
return null;
var index = reader.GetOrdinal(columnName);
return reader.GetString(index);
}
}
}
You can not. Command.ExecuteScalar take no parameters ..
What you can do is to use a text command and modify its CommandText property value to include the column you need to get:
command.CommandText = "SELECT " + columnName + " FROM Table WHERE Key = " + ...
You could create an extension method to do this for you. C# equiv (which I imagine you could translate to a VB.NET extension rather easily):
public static T ExecuteScalar<T>(this SqlCommand cmd, String columnName)
{
using(var reader = cmd.ExecuteReader())
{
var item = default(T);
if(reader.Read())
{
item = (T)dataReader.GetValue(dataReader.GetOrdinal(columnName))
}
return item;
}
}
... and invoke it like so:
var firstName = cmd.ExecuteScalar<String>("FirstName");
You should try the below code also.
Private Sub YourFunctionName()
Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
con.Open()
Using cmd As SqlCommand = New SqlCommand
Dim expression As String = "Parameter value"
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure"
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
cmd.Connection = con
Using dr As IDataReader = cmd.ExecuteReader()
If dr.Read() Then
Dim str As String = dr("YourColumnName").ToString()
End If
End Using
End Using
End Using
End Sub