I'm trying at the moment to get an information from a database and want to save it in a string, but yeah not sure about how really to do it right.
This is my code, where I open the LoadSql function:
public void LoadData(string KNR, string WNR, String filter)
{
// WHERE
const string sqlTemplate = "SELECT KUNDENAUFTRAGSNR FROM MESSFELD.AUSSTANDSDATEN WHERE FTNR = '" + txt_Barcode_read.Text + "'";
string sql = string.Format(sqlTemplate, filter);
Database cdb = new Database();
// try to connect and cancel on error
if (!cdb.Open("**********", "*********"))
{
SetStatusText("Datenbank ist nicht verfügbar.");
return;
}
WNR = cdb.LoadSql(sql);
cdb.Close();
}
And here is the LoadSQL function:
public DataTable LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
return dt;
}
catch
{
return null;
}
}
For the moment the LoadSQL is saving in datatable, how to change for saving the number in the string WNR?
You can re-write your LoadSQL function to something like this :
public string LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
rdr.Read();
if(rdr.HasRows)
return rdr.GetString(0);
else
return "";
}
catch
{
return null;
}
}
Related
A function in my app is returning a data table by joining the data tables getting from many other sub functions. Each sub functions are independent to each other with common primary key. Now, It takes nearly two minutes to execute the function for 50 of students. Please suggest me a best/fastest way to achieve the same.
public DataTable ShowReportOnGridivew(int class_id, string searchDate)
{
DataTable dt_students_List = null;
try
{
//====Main Table=====//
dt_students_List = GetDistinctStudentList(class_id);//there will be around minimum of 50 students
if (dt_students_List != null)
dt_students_List.PrimaryKey = new DataColumn[] { dt_students_List.Columns["student_id"] };
//Tables need to merge with main table
DataTable dt_CurrentRank = null;
DataTable dt_ScoreInEnglish = null;
DataTable dt_AcademicDetails = null;
DataTable dt_ExtraCurriculam = null;
DataTable dt_Attendance = null;
DataTable dt_Arts = null;
DataTable dt_FuelToBridger = null;
DataTable dt_FuelToAircraft = null;
DataTable dt_TeacherFeedback = null;
DataTable dt_TotalScore = null;
foreach (DataRow row in dt_students_List.Rows)
{
string student_id = row["student_id"].ToString();//primary key
//==========Current Rank================//
dt_CurrentRank = GetCurrentRank(student_id);//Binding data using sql
dt_CurrentRank.PrimaryKey = new DataColumn[] { dt_CurrentRank.Columns["student_id"] };
if (dt_CurrentRank != null)
{
dt_students_List.Merge(dt_CurrentRank);
}
//====== Score in English =====
dt_ScoreInEnglish = GetScoreInEnglish(student_id, searchDate);
dt_ScoreInEnglish.PrimaryKey = new DataColumn[] { dt_ScoreInEnglish.Columns["student_id"] };
if (dt_ScoreInEnglish != null)
{
dt_students_List.Merge(dt_ScoreInEnglish);
}
//====== Academic Details =====
dt_AcademicDetails= GetAcademicDetails(student_id);
dt_AcademicDetails.PrimaryKey = new DataColumn[] { dt_AcademicDetails.Columns["student_id"] };
if (ddt_AcademicDetails != null)
{
dt_students_List.Merge(dt_AcademicDetails);
}
//=====Similarly calling other functions and merging the columns to dt_students_List ======
}
}
catch (Exception show_error)
{
string log_data = "Response: Error- " + show_error.ToString();
obj.DatalogFile("StudentsList", log_data);
throw show_error;
}
return dt_students_List;
}
====== Each sub functions are written like below.=============
private async DataTable GetCurrentRank(string student_id)
{
DataTable dt = null;
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = null;
SqlDataReader dr = null;
string sql = string.Empty;
sql = "SELECT student_id,current_rank FROM student_details WHERE " +
" student_id = #student_id ";
cmd = new SqlCommand(sql, con);
con.Open();
try
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#student_id", student_id);
dr = cmd.ExecuteReader();
dt = new DataTable("CurrentRank");
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("student_id", typeof(int)),
new DataColumn("current_rank", typeof(float))});
if (dr.HasRows)
{
dt.Load(dr);
}
string log_data = "Web App Function: GetCurrentRank \n";
log_data += "Response: " + JsonConvert.SerializeObject(dt);
obj.DatalogFile("GetCurrentRank", log_data);
return dt;
}
catch (Exception show_error)
{
string log_data = "Response: Error- " + show_error.ToString();
obj.DatalogFile("GetCurrentRank", log_data);
throw show_error;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
You can write multiple select statement in single stored procedure;
and get output in DataSet.
You can get all your tables in a single request:
CREATE PROCEDURE Demo
**Parameters**
AS
-- Your all functions select statements
GO;
C#:
public DataSet GetDataSet(string ConnectionString, string SpName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SpName;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
///conn.Open();
da.Fill(ds);
///conn.Close();
return ds;
}
I'm trying to get all data from an SQL table and store it in a List using the C# programming language.
the SQL statement I'm using is:
private string cmdShowEmployees = "SELECT * FROM Employees;";
This is being used in the same class as a function
public List<string> showAllIdData()
{
List<string> id = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
id.Add(reader[0].ToString());
}
return id;
}
}
and here
public List<string> showAllActiveData()
{
List<string> active = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
active.Add(reader[1].ToString());
}
return active;
}
I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.
I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Any ideas?
If you must use the reader in this way, why not create an object which holds the table row data.
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
That way you can loop through with your reader as follows:
public List<SomeComplexItem> showAllActiveData()
{
List<SomeComplexItem> active = new List<SomeComplexItem>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
var someComplexItem = new SomeComplexItem();
someComplexItem.SomeColumnValue = reader[1].ToString();
someComplexItem.SomeColumnValue2 = reader[2].ToString();
someComplexItem.SomeColumnValue3 = reader[3].ToString();
active.Add(someComplexItem);
}
return active;
}
You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult();.
The database used is the standard Microsoft NorthWind database.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace SQL_Server_TwoList
{
public class DataOperations
{
public List<string> Titles { get; set; }
public List<string> Names { get; set; }
/// <summary>
/// Trigger code to load two list above
/// </summary>
public DataOperations()
{
Titles = new List<string>();
Names = new List<string>();
}
public bool LoadData()
{
try
{
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"
SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees];
SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Names.Add(reader.GetString(0));
}
// move on to second select
reader.NextResult();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Titles.Add(reader.GetString(0));
}
}
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Form code
namespace SQL_Server_TwoList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataOperations dataOps = new DataOperations();
if (dataOps.LoadData())
{
listBox1.DataSource = dataOps.Names;
listBox2.DataSource = dataOps.Titles;
}
}
}
}
You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.
Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
conn = new SqlConnection(Connstr);
try
{
string contents = "SELECT * FROM ..."
conn.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn); //create command using contents of sql file
da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds
DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database
try
{
//manipulate database
da_1.Fill(ds_1);
if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
{
for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
{
//rows[rownumber][column number/ "columnName"]
Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
}
}
}
catch(Exception err)
{}
conn.Close();
}
catch(Exception ex)
{}
A few months ago I made a test program for a project and everything worked fine there.
Now I am working on the program itself, so I copied the code from the test program and
changed the the names of the columns,buttons etc. so it would fit the current program.
When I try to add something into the database it does nothing on the first click, on the
second pops up an error which says that the connection is open.. I really got no idea what's
the problem. I tried to check again if I made a mistake in a column name or the database name
but everything seems to be correct.
Note: I also have a function that show data from the database and it works without any problem.
private void InsertData()
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
Connection.Open();
DataAdd.ExecuteNonQuery();
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
string NewRowNum()
{
string Row = RowFind();
int CalcRow = int.Parse(Row) + 1;
Row = CalcRow.ToString();
return Row;
}
The connection that appears to be open is the one in the string RowFind().
Here are the other related things to the database:
public partial class frmShop : Form
{
System.Data.SqlClient.SqlConnection Connection;
public frmShop()
{
string DatabaseConnection = WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1;
Connection = new System.Data.SqlClient.SqlConnection();
Connection.ConnectionString = DatabaseConnection;
InitializeComponent();
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
Connection.Open();
SqlDataReader ReadSentence = null;
Int32 BinaryInt = Int32.Parse(txtBinaryString.Text);
string CommandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
SqlCommand Command = new SqlCommand(CommandString, Connection);
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
ReadSentence = Command.ExecuteReader();
while (ReadSentence.Read())
{
txtSentence.Text = (ReadSentence["Sentence"].ToString());
Fit = 1;
}
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You are getting errors because you are reusing the same connection Connection.Open(); several times.
Your method InsertData() is doing this 3 times in the same method.
You should create a new instance of the connection object and dispose it on your methods.
Using Statement are the way to go.
private void InsertData()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
Connection.Open();
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
DataAdd.ExecuteNonQuery();
//Connection.Close(); no need to close
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You can save one more connection if you store the row returned by RowFind()
string RowFind()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
//Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
So you would connect once instead of twice:
var Row = RowFind();
string NewCode = GenerateCode(Row);
string NewRow = NewRowNum(Row);
string NewSentence = txtSentence.Text;
Declare your connection string variable to a property so you can reuse it:
private string DatabaseConnection {get; set;}
Instead using an instance level SqlConnection you should only provide a common factory for creating a connection:
public partial class frmShop : Form
{
private string ConnectionString
{
get { return WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1; }
}
public frmShop()
{
InitializeComponent();
}
private SqlConnection CreateConnection()
{
var conn = new SqlConnection(ConnectionString);
conn.Open();
return conn;
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
using (var conn = CreateConnection())
{
var BinaryInt = int.Parse(txtBinaryString.Text);
var commandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
using (var Command = new SqlCommand(commandString, conn))
{
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
using (var readSentence = Command.ExecuteReader())
{
while (readSentence.Read())
{
txtSentence.Text = (readSentence["Sentence"].ToString());
Fit = 1;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void InsertData()
{
try
{
using (var conn = CreateConnection())
{
var commandString = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
using (var comm = new SqlCommand(commandString, conn))
{
comm.Parameters.AddWithValue("#NewBinaryString", GenerateCode());
comm.Parameters.AddWithValue("#NewNewSentence", txtSentence.Text);
comm.Parameters.AddWithValue("#NewRowNumber", NewRowNum());
comm.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
using (var conn = CreateConnection())
{
var commandString = "SELECT * FROM ShopSentences";
using (var comm = new SqlCommand(commandString, conn))
{
using (var sda = new SqlDataAdapter(queryString, Connection))
{
using (DataTable dt = new DataTable("ShopSentences"))
{
sda.Fill(dt);
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
}
}
}
string NewRowNum()
{
var Row = RowFind();
var CalcRow = int.Parse(Row) + 1;
return CalcRow.ToString();
}
}
But this is just the beginning you should not have any hard SQL dependency in your Form classes.
When sharing same SqlConnection instance several times in your code, instead of directly opening the you can rather check the connection state first and then open it if not already opened. For example:
if(Connection.State!= ConnectionState.Open)
Connection.Open();
I am using the following code to consume a CUBRID database java stored procedure.
string ConnectionString = "server=localhost;database=demodb;port=30000;user=dba;password=123456";
DataTable dt = new DataTable();
DataSet ds = new DataSet();
CUBRIDConnection con = new CUBRIDConnection(ConnectionString);
CUBRIDCommand com = new CUBRIDCommand();
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.CommandText = "select rset()";
CUBRIDParameter pan = new CUBRIDParameter();
pan.Direction = ParameterDirection.Output;
pan.CUBRIDDataType = CUBRIDDataType.CCI_U_TYPE_RESULTSET;
pan.ParameterName = "?p1";
CUBRIDDataAdapter dap = new CUBRIDDataAdapter(com);
con.Open();
int val = dap.Fill(ds);
con.Close();
and in the server use the next function and stored procedure in the server
public class JavaSP3 {
public static ResultSet TResultSet(){
try {
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
Connection con = DriverManager.getConnection("jdbc:default:connection:");
String sql = "select * from athlete";
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
((CUBRIDResultSet)rs).setReturnable();
return rs;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
and the function code is this
CREATE FUNCTION "rset"() RETURN CURSOR
AS LANGUAGE JAVA
NAME 'JavaSP3.TResultSet() return cubrid.jdbc.driver.CUBRIDResultSet'
I run this with a function that result a string and return the value, but when I change to CUBRIDResultSet value dont work and CUBRID says>
execute error:-911
line 1 is not executed (error)
Error description:
Invalid call: it can not return ResultSet.
Please, I have 3 days trying to solve this any one can help me?
ADO.NET dont provide support for ResultSet.
http://www.cubrid.org/?mid=forum&category=195532&document_srl=358924
using System.Data;
using CUBRID.Data.CUBRIDClient;
using System.Data.Common;
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string ConnectionString = "server=localhost;database=demodb;port=30000;user=dba;password=123456";
DataTable dt = new DataTable();
DataSet ds = new DataSet();
CUBRIDConnection con = new CUBRIDConnection(ConnectionString);
CUBRIDCommand com = new CUBRIDCommand();
com.CommandType = CommandType.Text; //Important ADO.NET driver crash using call convention
com.Connection = con;
com.CommandText = "select rset();";
CUBRIDParameter pan = new CUBRIDParameter();
con.Open();
DbDataReader reader = com.ExecuteReader();
CustomAdapter da = new CustomAdapter();
da.FillFromReader(dt, reader);
con.Close();
DataRow fila = dt.Rows[0];
Console.WriteLine(fila[0].ToString());
Console.ReadKey();
}
}
public class CustomAdapter : System.Data.Common.DbDataAdapter
{
public int FillFromReader(DataTable dataTable, IDataReader dataReader)
{
return this.Fill(dataTable, dataReader);
}
protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow a, IDbCommand b, StatementType c, System.Data.Common.DataTableMapping d)
{
return (System.Data.Common.RowUpdatedEventArgs)new EventArgs();
}
protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow a, IDbCommand b, StatementType c, System.Data.Common.DataTableMapping d)
{
return (System.Data.Common.RowUpdatingEventArgs)new EventArgs();
}
protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value)
{
}
protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value)
{
}
}
java class
import java.sql.*;
import cubrid.jdbc.driver.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class JavaSP3 {
public static String TResultSet(){
ResultSet rs = null;
Statement stmt = null;
String sql;
try {
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
Connection con = DriverManager.getConnection("jdbc:default:connection:");
((CUBRIDConnection)con).setCharset("euc_kr");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
sql = "select * from athlete";
stmt=con.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int ii = 1; ii <= colCount; ii++) {
String columnName = rsmd.getColumnName(ii);
Object value = rs.getObject(ii);
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
}
}
String valor = getDocumentAsXml(doc);
return valor;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static String getDocumentAsXml(Document doc)
throws TransformerConfigurationException, TransformerException {
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
}
Cubrid function
CREATE FUNCTION "rset"() RETURN STRING
AS LANGUAGE JAVA
NAME 'JavaSP3.TResultSet() return java.lang.String'
This allow you get data from Java stored procedures in CUBRID using ADO.NET
I've been unsuccessfully trying to bind a gridview through a web service, but nothing's showing up. Is there something wrong with my web method?
Here are what I have in my App_Code folder: membershipService.cs, DataAccessService.cs, Post.cs
membershipService.cs:
[WebMethod(Description = "Display all users' post")]
public Post[] DisplayAllPosts()
{
List<Post> usersPosts = new List<Post>();
DataSet ds;
Post p;
try
{
ds = DataAccessService.RunSimpleQuery("SELECT username, post, postDateTime FROM UserPosts ORDER BY postID DESC");
foreach (DataRow dr in ds.Tables[0].Rows)
{
p = new Post();
p.username = dr["username"].ToString();
p.post = dr["post"].ToString();
p.postDateTime = dr["postDateTime"].ToString();
usersPosts.Add(p);
}
return usersPosts.ToArray();
}
catch (Exception ex)
{
return null;
}
}
DataAccessService.cs:
public static DataSet RunSimpleQuery(string query)
{
DataSet result = new DataSet();
OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(ConnectionString);
OleDb.OleDbCommand command;
OleDb.OleDbDataAdapter dataAdapter;
try
{
//open database connection
connection.Open();
//create database command for query
command = new OleDb.OleDbCommand();
command.CommandText = query;
command.Connection = connection;
command.CommandType = CommandType.Text;
//create data adapter and use it to fill the data set using the command
dataAdapter = new OleDb.OleDbDataAdapter();
dataAdapter.SelectCommand = command;
dataAdapter.Fill(result);
}
catch
{
result = null;
}
finally
{
//close connection
connection.Close();
connection.Dispose();
}
//return dataset
return result;
}
Post.cs:
public class Post
{
public string username;
public string post;
public string postDateTime;
}
I'll appreciate any help I can get. Thank you!
have you tried putting a breakpoint on the exception handler in DisplayAllPosts to see if an exception is being thrown there?
Unless all of your database columns are non-nullable, you could have a DbNull.Value in one of your columns that is throwing an exception.