How to get data in string from database - c#

i am working on android client and .NET server application, in which i parse data into xml and then convert into string and then send this string to android client.now i am facing problem in getting data from SQL Server in xml format and convering it into string.here is my code..
UserLogin userLogin = converter.GetObjectFromXml<UserLogin>(xml);
String query = #"Select StdBD.First_NameEn As name from TblStudentBioData As StdBD Join TblStudentDetail As StdDet ON StdBD.Student_ID = StdDet.Student_ID
join TblClassSchedule As ClsSch on StdDet.ClassID = ClsSch.ClassSchID
join TblClass As Cls on ClsSch.ClassID = Cls.ClassID
join TblSemAssigning As SemAs on SemAs.SemAssId = ClsSch.SemAssId
join TblAcademicYear As Acd on SemAs.AcademicYearId = Acd.AcademicYearId
where Acd.AcademicYearId = " + userLogin.userId + "FOR XML RAW('Student'),Root('Students'),Elements";
String outputXml = General.ExecuteSimpleSelectQuery(General.connectionString, query, "Table user");
Console.WriteLine("xmllll = "+outputXml);
and
class General
{
public static String ServerIp = "192.168.1.2";
public static String ServerPort = "8060";
public static String connectionString = NetService2.Properties.Settings.Default.ConnString.ToString();
public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(_Query,conn);
SqlDataReader reader = null;
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("name = " + reader[0].ToString());
}
reader.Close();
conn.Close();
return "";
}
Output:
by using this code i am getting data in SqlDataReader instance but not in string,so is there any way to directly get data into string or convert SqlDataReader instance data into string,so i can use it.
i want output like this:
String xml = "<Students>
<Student>
<name>Aliya</name>
</Student>
<Student>
<name>Fahad</name>
</Student>
<Student>
<name>iqra</name>
</Student>
<Student>
<name>iqra</name>
</Student>
<Student>
<name>khurram</name>
</Student>
<Student>
<name>Zainab</name>
</Student>
<Student>
<name>Fatima</name>
</Student>
<Student>
<name>Fahad</name>
</Student>
</Students>";
replace this hard coded xml to the xml, getting from database.

just get your XML data in a DataTable it will give you an xml at its first position and then convert it into an string.
SqlConnection conn = new SqlConnection(yourConnectionString);
SqlCommand cmd = new SqlCommand(your query,conn);
SqlDataAdapter SDA = new SqlDataAdapter();
DataTable dt = new DataTable(DataTableName);
conn.Open();
SDA.Fill(dt);
conn.Close();
String xml = dt.Rows[0].ItemArray[0].ToString();
return xml;

Simple put your query into storedprocedure
Create PROCEDURE yourprocedurename
AS
BEGIN
Select StdBD.First_NameEn As name from TblStudentBioData As StdBD
Join TblStudentDetail As StdDet ON StdBD.Student_ID = StdDet.Student_ID
join TblClassSchedule As ClsSch on StdDet.ClassID = ClsSch.ClassSchID
join TblClass As Cls on ClsSch.ClassID = Cls.ClassID
join TblSemAssigning As SemAs on SemAs.SemAssId = ClsSch.SemAssId
join TblAcademicYear As Acd on SemAs.AcademicYearId = Acd.AcademicYearId
where Acd.AcademicYearId = " + userLogin.userId + "FOR XML
RAW('Student'),Root('Students'),Elements";
END
and from coding side do something like this
public static String ExecuteSimpleSelectQuery(string ConnectionString,
string _Query, string DataTableName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand("yourstoredprocedurename",conn);
SqlDataAdapter SDA = new SqlDataAdapter();
DataTable dt = new DataTable(DataTableName);
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
SDA.SelectCommand = cmd;
SDA.Fill(dt);
conn.Close();
return dt.Rows[0].ItemArray[0].ToString();
}
hopefully it will give you the required output

You could use String.Join after you've loaded all records into a List<string>:
public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
{
List<string> list = new List<string>();
using(SqlConnection conn = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(_Query, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add("name = " + reader.GetString(0));
}
}
}
return string.Join(Environment.NewLine, list);
}
However, don't use string concatenation for your sql commands because you are vulnerable to sql-injection. So don't pass the query to the method ExecuteSimpleSelectQuery. Instead use sql-parameters.

Your function will always return empty string as you return "" after every time function is called. Try change your function as:
public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(_Query,conn);
string result;
conn.Open();
var dt = new DataTable();
dt.Load( cmd.ExecuteReader());
using (StringWriter sw = new StringWriter()) {
dt.WriteXml(sw);
result = sw.ToString();
}
conn.Close();
return result;
}

Yes, you can capture your column data into a string. By default, all of your data types will be considered an object. Which means you'll have to:
Use the SqlDataReader built in function.
Use the ToString()
Use a (string) or as string Cast.
Before I provide an example, something you should do before you attempt to work with the data, a null check.
if(reader[0] != DBNull.Value)
{
// Do Something...
}
The reason, is if you perform certain manipulations on the data you'll receive an Exception. Another useful thing, wouldn't be to use [0] but rather the ["NameOfColumn"] as later on maintaining the code, will make the specific data easier to read and see what it does.
if(reader["NameOfColumn"] != DBNull.Value)
example = reader["NameOfColumn"].ToString();
if(reader["NameOfColumn"] != DBNull.Value)
example = (string)reader["NameOfColumn"];
example = reader["NameOfColumn"] as string;
Those are some primitive examples, the last one if it fails will assign a null. So you'll want to anticipate that bubbling potentially in your code. The first example, is the most common and simple.
However, if you want to avoid repeating said code.
public static class DataReaderExtension
{
public static string GetStringOrNull(this IDataReader reader, int ordinal)
{
var value = null;
if(!reader.IsDBNull(reader.GetOrdinal(ordinal)
reader.GetString(ordinal);
return value;
}
public static string GetStringOrNull(this IDataReader reader, string columnName)
{
return reader.GetStringOrNull(reader.GetOrdinal(columnName));
}
}
Those are several different approaches. Hopefully that indeed helps you.

Related

How to solve The name "connectionclass" does not exist in the current context?

So, I want to make a drop down list. I have the connectionclass.cs, which connects the database to an array list. But when I build the dropdown list, doesn't find the connectionclass
Sorry, i am a bit tired. So, this is the classconnection.cs.
There is the ss
namespace YourCoffeeShop.App_Code
{
public static class ConnectionClass
{
private static SqlConnection conn;
private static SqlCommand command;
static ConnectionClass()
{
string connectionString = ConfigurationManager.ConnectionStrings["cafeaconnection"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
}
public static ArrayList GetCafeaByType(string cafeaType)
{
ArrayList list = new ArrayList();
string query = string.Format("SELECT * FROM tipuridecafea WHERE tip LIKE '{0}'", cafeaType);
try
{
conn.Open();
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
int id = reader.GetInt32(0);
string nume = reader.GetString(1);
string tip = reader.GetString(2);
double pret = reader.GetDouble(3);
string roast = reader.GetString(4);
string tara = reader.GetString(5);
string imagine = reader.GetString(6);
string review = reader.GetString(7);
cafeacs tipuridecafea = new cafeacs(id, nume, tip, pret, roast, tara, imagine, review);
list.Add(tipuridecafea);
}
}
finally
{
conn.Close();
}
return list;
}
You did not post your entire class, but the answer is that C# is case-sensitive, so:
ArrayList shirtList = connectionclass.GetShirtByType(DropDownList1.SelectedValue);
is not equivalent to:
ArrayList shirtList = ConnectionClass.GetShirtByType(DropDownList1.SelectedValue);
Provided that the .GetShirtByType(...) method exists in the class and is static, the second example above would correct your error.
I discovered what the problem was. I went into ConnectionClass.cs properties and changed the build action to compile and then added the using YourCoffeeShop.App_Code. It works now, thanks everyone!

Initializing Combo Box in C# Access

I was trying to add a combo box which could get all the product name but unfortunately I follow some tutorials and end up like this.
void fillCombo()
{
try
{
con.Open();
OleDbCommand command = new OleDbCommand("Select * from IblInventory");
command.Connection = con;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
String product = reader.GetString("ProductName"); // << invalid argument
cmbProduct.Items.Add(product);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
What could possibly the reason?
From the documentation of OleDbDataReader.GetString you will notice that the argument required by the method is an integer representing the position of the column in the returned record not its name.
If you (rightly) prefer to use the column name then you need to take a detour and use the GetOrdinal method to retrieve the position of the column given the name.
while (reader.Read())
{
int pos = reader.GetOrdinal("ProductName");
String product = reader.GetString(pos);
cmbProduct.Items.Add(product);
}
Another example, practically identical to your situation, can be found in the documentation page on MSDN about OleDbDataReader.GetOrdinal
It is also a common practice to write an extension method that allows you to write code as yours hiding the details of the mapping between name and position. You just need a static class with
public static class ReaderExtensions
{
public string GetString(this OleDbDataReader reader, string colName)
{
string result = "";
if(!string.IsNullOrEmpty(colName))
{
int pos = reader.GetOrdinal(colName);
result = reader.GetString(pos);
}
return result;
}
... other extensions for Int, Decimals, DateTime etc...
}
Now with this class in place and accessible you can call
string product = reader.GetString("ProductName");
it is working in my project
First fill your data in to datatable see the below code
DataTable results = new DataTable();
using(OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("Select * from IblInventory", conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
Now
cmbProduct.DataSource = results ;
cmbProduct.DisplayMember = "ProductName";
cmbProduct.ValueMember = "Id feild of IblInventory table";

cek valid data in table with input ";" and where in

i want to check valid data...
i have a table Divisi with sample data like this:
=====================
IdDivisi NamaDivisi
=====================
1 DivisiA
2 DivisiB
3 DivisiC
in my code, i get value :
string data = DivisiA;DivXXX
so, when checked, the alert will appear invalid data.
I want to get a query like this:
select NamaDivisi from Divisi where NamaDivisi IN('DivisiA','DivXXX')
and the result is null or empty or invalid.
because there are values ​​/ data 'DivXXX' is not valid on the table Divisi
But this time, when I debug, I get the query result like this:
select NamaDivisi from Divisi where NamaDivisi IN ('DivisiA;DivXXX')
===================================================
This is the full code.
private string CekValidDivisi(string data)
{
DivisiFacade div = new DivisiFacade();
string getDivisi = div.CekValidData(data);
return getDivisi;
}
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + data + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
please help me to resolve the problem in my code. thank you ...
You have multiple problems in your code, but this is not a place to teach you basics, so I'll try to stick to the topic. If you want to have a parameter like that, you have to create it like that first. I guess the data contains string with value DivisiA;DivXXX (and I presume DivXXX is just a generic name meaning you have multiple divisions there). Probably the easiest way would be to do something like this with it
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string paramData = ParseData(data);
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + paramData + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
private string ParseData(string data)
{
return data.Replace(";", "','");
}
Haven't tried it, but hope you get the idea. Either way, please for your own sake, do some research on what is the best way to handle sql connections in c# and also how to prevent SQL injections.

C# web service that gets data from SQL Server 2008 by select query and save it in xml file

I want to write a C# web service that gets data from a SQL Server 2008 with a select query and saves it in a XML file. Note: I use LinQ.
How can I do that?
I used this code but it had more errors .
[WebMethod]
public bool Search(string XmlSearch)
{
using (var MyCon = new MainContextDataContext())
{
MyCon.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["HQ_TestConnectionString"].ConnectionString;
XElement SearchCust = XDocument.Parse(XmlSearch).Root.Elements().First();
string AccountNumber = SearchCust.Element("Customer").Attribute("AccountNumber").Value;
string Phone = SearchCust.Element("Customer").Attribute("PhoneNumber").Value;
string Name = SearchCust.Element("Customer").Attribute("FirstName").Value;
if (MyCon.Customers.Where(i => i.AccountNumber == AccountNumber).Count() > 0)
{
SqlConnection MyConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HQ_TestConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT customer.AccountNumber, ShipTo.Address, ShipTo.Address2 FROM Customer FULL OUTER JOIN ShipTo ON customer.AutoID = ShipTo.AutoID WHERE customer.AccountNumber = " + AccountNumber, MyConn);
cmd.Connection.Open();
object value = cmd.ExecuteScalar();
MyConn.Close();
SqlDataReader Reader = cmd.ExecuteReader();
string SRD = string.Empty;
if (Reader.HasRows)
{
if (Reader.Read())
{
SRD = Reader.ToString();
}
}
Reader.Close();
System.Xml.XmlDocument Xdoc = new System.Xml.XmlDocument();
Xdoc.InnerXml = SRD;
Xdoc.Save("d:\\xmltest.xml");
}
return false;
}
}

Retrieve distinct row and declaring scalar variable

I am trying to retrieve a distinct row from my Database from a particular "deliverySerial".
However I encountered an error which prompt me to "Declare Scalar Variable ="#deliverySerial".
I had tried many other ways but still problems still persist.
Here is the connection:
public class DlDbConn
{
public DlDbConn()
{
}
public SqlConnection GetConnection()
{
SqlConnection dbConn;
dbConn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\test.mdf;Integrated Security=True;User Instance=True");
return dbConn;
}
}
Method in the data layer:
private String errMsg;
private DlDbConn dbConn;
public testing()
{
dbConn = new DlDbConn();
}
public DataSet Details(String supplierLogo, String supplierName, String supplierAddr, int poNum, String dateSent, int deliverySerial, String deliveryDate,
int quantity, String catSerial, String catName)
{
SqlConnection conn;
StringBuilder sql;
SqlDataAdapter da;
DataSet detail;
conn = dbConn.GetConnection();
detail = new DataSet();
sql = new StringBuilder();
sql.AppendLine("SELECT * FROM (select PO.poNum, PO.dateSent, ViewDelivery.deliverySerial, Supplier.supplierName, Supplier.supplierAddr, Supplier.supplierLogo, ViewDelivery.deliveryDate, Catalog.catSerial, Catalog.catName, PO.quantity, ROW_NUMBER() OVER (PARTITION BY Catalog.catSerial ORDER BY Catalog.catSerial) AS num FROM PO INNER JOIN Supplier ON PO.supplierID = Supplier.supplierID INNER JOIN ViewDelivery ON PO.poNum = ViewDelivery.poNum INNER JOIN Catalog ON PO.catSerial = Catalog.catSerial)AS a WHERE a.num = 1 ");
sql.AppendLine("AND ViewDelivery.deliverySerial = #deliverySerial");
try
{
conn.Open();
da = new SqlDataAdapter(sql.ToString(), conn);
da.SelectCommand.Parameters.AddWithValue("#deliverySerial", deliverySerial);
da.Fill(detail);
}
catch (Exception ex)
{
errMsg = ex.Message;
}
finally
{
conn.Close();
}
return detail;
}
You must use parameter notation for MySQL i.e. ? instead of #deliverySerial in your query.
Also, table ViewDelivery not accessible in outer part of query.
Use:
AND a.deliverySerial = ?
I think your query is incorrect. Here is the Fiddle -- you can't query on ViewDelivery since it's outside of your subquery.
Try removing that from your WHERE criteria since that field is returned in your subquery:
sql.AppendLine("AND deliverySerial = #deliverySerial");
I don't think you need the "?", but I could be mistaken.
Good luck.

Categories

Resources