I have a table with columns below,
SALES_ORDERS.ORDER_SLIP.NUMBER|SALES_ORDERS.ORDER_SLIP.DATE|SALES_ORDERS.ORDER_SLIP.ARP_CODE
and the XML output I need to have is like below
<SALES_ORDERS>
<ORDER_SLIP>
<NUMBER>TEST</NUMBER>
<DATE>02.09.2014</DATE>
<ARP_CODE>CARI1</ARP_CODE>
</ORDER_SLIP>
</SALES_ORDERS>
I need to create the xml according to column name which include full path way from the top.
How can I achive such an XML file from such a table? I can use LINQ if it is necessary but I am not sure how to do it?
Too Easy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string SQL = "Enter Your SQL Select string here";
string connStr = "Enter You connection string here";
SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
DataSet ds = new DataSet();
adapter.Fill(ds);
ds.DataSetName = "SALES_ORDERS";
ds.WriteXml(FILENAME, XmlWriteMode.WriteSchema);
}
}
}
Related
I am trying to connect to a database in C# and bring up certain data points. The database has numerous columns and tables and I simply want to display them in the console using Writeline(). Below is what I have so far. The code runs without error but does not display anything either.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Sql;
namespace SQLIntro
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection("Server=[SQ_SIXTEEN];Database=[PocketCentral];User ID=[un];Password=[pw];Trusted_Connection=true"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM tbl_Terminal", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
}
Console.WriteLine();
}
}
}
}
}
}
}
The one thing is where the column info would go...The SQL command? or in the while loop?.
That code would actually throw an exception. You have surrounded the names with brackets in your connection string which would cause the connection to fail. Change it to:
using (SqlConnection connection = new SqlConnection("Server=SQ_SIXTEEN;Database=PocketCentral;Trusted_Connection=true"))
Note that when Trusted_Connection is true (windows authentication) you don't use UserID and Password.
EDIT: Additional notes.
You would normally know your data content (your columnname and types). From SQL viewpoint it is suggested that you should list all your columns. ie: Instead of simply using "select *" use something like "select firstName, lastName, ... from ...".
As per the reader, instead of reader.GetValue[i] you use reader[index] and cast the type to what it should be like:
(int)reader[0]
(DateTime)reader["OrderDate"]
Integer indexing is faster but depends on column position where string indexing with column name is more readable.
EDIT2: Don't skip looking into LINQ. It is easier IMHO.
I am looking to use the SQL Data adapter feature inside of MVC to display the results from a query string inside of my project. I'm new to using the sql adapter feature but I would like to get used to it. Simply put, I need to know what to put in my controller, and if i need to create a model, and what to put in my view.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace NewHoyaIntranet.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
DataSet data;
DataTable table;
using (SqlConnection connection = new
SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HUT"]
.ConnectionString))
{
connection.Open();
SqlCommand select = new SqlCommand("SELECT * FROM HUT.dbo.XREF_HIOI_LensStyle_HTL", connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = select;
data = new DataSet();
adapter.Fill(data, "HUT.dbo.XREF_HIOI_LensStyle_HTL");
table = data.Tables[0]; //is the [0] really correct?
}
return View(/* Right now nothing is returning in any view/ how do i tie the view in? */);
}
}
}
I've tried to find the answer to this but I've found no success. If it is possible how do you convert a string to a data set in C# so I can generate a JSON file from the data in my database table.
Here is my asmx file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Data;
using System.Data.SqlClient;
namespace Book
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Service : System.Web.Services.WebService
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public DataSet GetBookList()
{
con = new SqlConnection(#"Data Source=server;Initial Catalog=database;Persist Security Info=True;User ID=username;pwd=password;");
adap = new SqlDataAdapter("SELECT * FROM tblBookList", con);
ds = new DataSet();
adap.Fill(ds, "tblBookList");
var jsonString = new JavaScriptSerializer().Serialize(ds);
return jsonString;
}
}
}
Or is there a smarter way to export the data into a JSON file?
EDIT
The error that I am receiving is
Error: cannot implicitly convert type 'string' to 'System.Data.DataSet'
The error appears on the 'return jsonString;' statement.
Your function is defined as returning a DataSet.
You are returning a string.
Change the function definition to return a string.
public String GetBookList()
If you want to return the DataSet, just return the "ds" variable. Otherwise you are just returning a string that is a serialized version of the ds variable.
for this i am not getting any output thought there is not any error or warning... i guess the problem is with connection string but not sure, is it?? i have created a database name RV(.mdf file) in SQL server data tool and connected it to this project in visual studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;
namespace student_TableConnectTry1
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =#"Data Source=(local);Integrated Security=SSPI;" +"Initial Catalog=RV";
cn.Open();
string strSQL = "Select * From student";
SqlCommand myCommand = new SqlCommand(strSQL, cn);
using (SqlDataReader myDataReader = myCommand.ExecuteReader())
{
// Loop over the results.
while (myDataReader.Read())
{
Console.WriteLine("-> usn: {0}, name: {1}.",
myDataReader["usn"].ToString(),
myDataReader["name"].ToString()
);
}
}
Console.ReadLine();
}
}
}
}
You can use following connection string and try:
Integrated Security=SSPI;Persist Security Info=False;User ID=youruserid;Initial Catalog=databasename;Data Source=.\SQLEXPRESS
Also see the following link for connectionstring:
http://www.connectionstrings.com/sql-server/
I hope it will help you. :)
Let me know if it does not help you.
I'm trying to query the Windows Search 4.0 using sql. The property
of interest for me is: System.Search.QueryFocusedSummary.
I'm trying to read this property from the SystemIndex. I get a "column does not exist" error message. I am able to read other columns such as: System.Search.AutoSummary.
I am using the Microsoft Windows Search 3.x SDK download
(Windows.Search.Interop.dll) on a Windows 7 operating System and Windows
Search 4.0.
My query is:
SELECT TOP 25 System.QueryFocusedSummary From SystemIndex where
CONTAINS('microsoft') ORDER BY System.ItemDate DESC
How can I get the query working with System.Search.QueryFocusedSummary?
The code is as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Security.Permissions;
using System.Text;
using Microsoft.Search.Interop;
namespace QueryFocusedSummaryTest
{
class Program
[Stathread]
static void Main(string[] args)
{
string sqlQuery = "select top 25 System.Search.QueryFocusedSummary from SystemIndex where contains('microsoft') order by System.ItemDate DESC";
CSearchManager manager = new CSearchManager();
ISearchCtalogManager catalogMaager = manager.GetCatalog("SystemIndex");
ISearchQueryHelper queryHelper = catalogManager.GetQueryHelper();
using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString))
{
conn.Open();
using (OleDbCommand command = new OleDbCommand(sqlQuery, conn))
{
OleDbDataAdapter ds = new OleDbDataAdapter(command);
DataSet ds = new DataSet();
ds.Fill(ds);
command.ExecuteNonQuery();
//By now it has thrown the exception saying that the column is not found.
}
}
}
}
Here is a link about columns available for oledb interface:
https://web.archive.org/web/20120615190325/http://www.ariankulp.com/downloads/WindowsShellOLEProperties.txt
Seems System.Search.QueryFocusedSummary is not exposed, while System.Search.AutoSummary is. Maybe that's why you can't get the column.