Can I use a local DataTable with one column in sql query? And how?
List<int> k_p = null;
k_p = new List<int>();
k_p = (List<int>)Session["kosarica"];
DataTable spremljeno = new DataTable();
spremljeno.Columns.Add("id_k_p");
for(int i=0; i<k_p.Count; i++)
{
spremljeno.Rows.Add(k_p[i]);
}
String ConnString = "Data Source=BRACO-PC\\SQL1;Initial Catalog=DiplomskiSQL1SQL;Integrated Security=True;";
SqlConnection Conn = new SqlConnection(ConnString);
Conn.Open();
DataTable ukosarici = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select Proizvod.id_p, Proizvod.ime, TipProizvoda.tip, Proizvod.dimenzije, Proizvod.cijena FROM Proizvod LEFT JOIN TipProizvoda ON Proizvod.tip=TipProizvoda.id_t WHERE Proizvod.id_p IN #spremljeno", Conn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
da.Fill(ukosarici);
GridView1.DataSource = ukosarici;
GridView1.DataBind();
Conn.Close();
I want to show only data where id_p is equal to values in spremljeno, and do not want to do a temp table in db, but dont know if it is possible... Connecting to SQL server 2008...
You could add all ID's as parameter to an IN clause in SQL:
var parameters = new string[k_p.Count];
using(var cmd = new SqlCommand())
{
for (int i = 0; i < k_p.Count; i++)
{
parameters[i] = string.Format("#id_p{0}", i);
cmd.Parameters.AddWithValue(parameters[i], k_p[i]);
}
var sql = "Select Proizvod.id_p, Proizvod.ime, TipProizvoda.tip, Proizvod.dimenzije, Proizvod.cijena FROM Proizvod LEFT JOIN TipProizvoda ON Proizvod.tip=TipProizvoda.id_t WHERE Proizvod.id_p IN ({0})";
cmd.CommandText = string.Format(sql, string.Join(", ", parameters));
using(var con = new SqlConnection(connStr))
{
cmd.Connection = con;
using(var da = new SqlDataAdapter(cmd))
{
da.Fill(ukosarici);
}
}
}
Note that you should use using-statements for everything that implements IDisposable(f.e. SqlConnection, Dispose also closes the connection). Also note that i used only your List<int>, the second DataTable was redundant.
Related
I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.
I'm trying to get data from a SQL Server database and return data (all data) based on a query as follows:
public async Task<List<PersonEntity>> GetDataAsync()
{
var allUsers = new List<PersonEntity>();
SqlConnection conn = new SqlConnection("");
conn.Open();
SqlCommand cmd = new SqlCommand("Select* from <TABLE> <WHERE>", conn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var a = new PersonEntity {
LocationAreaCode = reader.GetString(0),
PersonStatusCode = reader.GetString(1),
PersonStatusDesc = reader.GetString(2)
};
allUsers.Add(a);
}
}
else
{
// no data found
}
reader.Close();
conn.Close();
return allUsers;
}
Is there a better way (in terms of performance) to read all data (values from all the columns) matching the query and return the data from this function?
You need to use ADO.net SqlDataAdapter Class
var ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "Select * from <table-name> where location = 'US'";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
I'm trying to get data from a SQL Server database and return data (all data) based on a query as follows:
public async Task<List<PersonEntity>> GetDataAsync()
{
var allUsers = new List<PersonEntity>();
SqlConnection conn = new SqlConnection("");
conn.Open();
SqlCommand cmd = new SqlCommand("Select* from <TABLE> <WHERE>", conn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var a = new PersonEntity {
LocationAreaCode = reader.GetString(0),
PersonStatusCode = reader.GetString(1),
PersonStatusDesc = reader.GetString(2)
};
allUsers.Add(a);
}
}
else
{
// no data found
}
reader.Close();
conn.Close();
return allUsers;
}
Is there a better way (in terms of performance) to read all data (values from all the columns) matching the query and return the data from this function?
You need to use ADO.net SqlDataAdapter Class
var ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "Select * from <table-name> where location = 'US'";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}
I created a stored procedure so as to return me a table.
Something like this:
create procedure sp_returnTable
body of procedure
select * from table
end
When I call this stored procedure on the frontend what code do I need to write to retrieve it in a datatable object?
I wrote code something like the following. I basically want to know retrieving and storing table into an object of datatable. All my queries are running, but I don't know how to retrieve table into a datatable through a stored procedure
DataTable dtable = new DataTable();
cmd.Connection = _CONN;
cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
OpenConnection();
adp.Fill(dtTable);
CloseConnection();
Here in this code a command has been bound with the stored procedure name and its parameters. Will it be returning me a datatable from the stored procedure?
string connString = "<your connection string>";
string sql = "name of your sp";
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
using(SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows) {
//manipulate your data
}
}
}
catch(SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch(Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Modified from Java Schools Example
Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}