I am not unable to understand the way in which a select * query is written while we create a web service using C#.NET to connect to an SQL Database.
Basically, I have 4 columns . I am taking a particular input from the user , which is an existing value of 1st column. Now depending on that value I want to select all the records of the remaining 3 columns. I need to write a SELECT * query but I don't in what form will I get those records. I have heard of SqlDataAdapter but then will it return me the records in a row-column format or do have to store the result in some sort of List and then use it for other purposes.
Can someone please help me to understand how such a query can be written?
This code is wrong but it will help understand what I need
I want to get the records of other columns based upon my "where clause" condition
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace statistics
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public int retrieve(String rollno)
{
int rows=0;
SqlConnection myConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
try
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
String strsql = "SELECT * FROM checkrecord values WHERE rollno=#rollno";
DataSet dataSet = new DataSet();
SqlDataAdapter dataAdapter = new SqlDataAdapter(strsql, myConnection);
myCommand.Parameters.Add("#rollno", SqlDbType.VarChar).Value = rollno;
rows = myCommand.ExecuteNonQuery();
SqlDataReader myReader = myCommand.ExecuteReader()
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
myConnection.Close();
}
return rows;
}
}
}
You need to connect to the database, then use SQLDataAdapter to send the user input SELECT query to the database. Something like,
SELECT col2,col3,col4 FROM yourtable WHERE col1 = ?
There are different ways to use the SQLDataAdapter, and specify the query and parameters. The SQLDataAdapter will return a DataSet that contains a DataTable. You can then use the DataSet or DataTable to populate the control of your choice (ie; DataGrid) with the results. There is a walk-through of this on MSDN: http://msdn.microsoft.com/en-us/library/aa984467%28v=vs.71%29.aspx
Based on your edit, you don't want to use ExecuteNonQuery. To get the rows you use ExecuteReader. Example here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader%28v=VS.71%29.aspx
I think you are talking about the return type of the webservice?
Yes, the database query will return you a list of the record values. With the .net webservices however, you can put these values into a custom class written by you, and the structure of this class will be included in your webservice.
[WebMethod]
public Myclass retrieve(String rollno)
{
return new Myclass("variable1", "variable2");
}
It will be included in the WSDL and thus can be implemented by any other application using your web service.
I recommend looking at the documentation for the class in question, in this case, the SQLDataAdapter
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx
What I think you might want is to fill the results into a dataset.
Related
Just started using windows 11 and installed Oracle drivers for 32Bit and 64Bit, wrote program using C# to fetch data from Oracle database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.Odbc;
using System.Data;
using System.Data.SqlClient;
namespace ApexAutoEmailConsol
{
static class ServiceLog
{
static String connectionString = "Dsn=Prod21_32;uid=ebseb;pwd=ebseb";
static string strQuery = string.Empty;
public static string OutstandingInvoices()
{
try
{
OdbcConnection oCon = new OdbcConnection();
oCon.ConnectionString = connectionString;
oCon.Open();
DataTable dtSales = new DataTable();
strQuery = "SELECT * from apps.org_organization_definitions HO";
// if I run above query in Toad it's giving result.
OdbcDataAdapter myAdp = new OdbcDataAdapter(strQuery, oCon);
myAdp.Fill(dtSales);
//Adapter not filling data to the datatable.
if (dtSales.Rows.Count <= 0)
{
return "";
}
return strReturn;
}
catch (Exception Ex)
{
WriteErrorLog(Ex.ToString());
return "";
}
}
}
When I copy strQuery and run on Toad, getting result but datatable is still empty.
What is the problem? The same code is working perfect on my Windows10 machine.
UnCOMMITted data is only visible within the session that created it (and will ROLLBACK at the end of the session if it has not been COMMITted). If you can't see the data from another session (C#) then make sure you have issued a COMMIT command in the SQL client (Toad).
If you have issued a COMMIT and still can't see the data then make sure that both the SQL Client (Toad) and the C# program are connecting to the same database and are querying the same user's schema of that database.
It's very unique problem, I had it around 2 years ago with my another machine, where I was not able to get some query result in Toad. Some queries are working but some of with specific table in joing was giving empty result. That time I added following language setting in my environment variable and was worked.
NLS_LANG = American_America.UTF8
Used same in my new machine and now am getting result with Visual Studio 2022.
I have a table which has the results of student's marks for particular modules (classes).
I take the mark percentage and multiply it against a value from the assessment table (based on the assessment ID). This part all works fine.
I tried to write a loop using the SQL data reader, to add up all the values FOR EACH MODULE. However, I can only seem to add up all the values altogether for a particular user (it's in the where clause). I can't put the moduleID = 1 in the WHERE clause because I need to see all results at once.
Here's the code I've already attempted, which adds up all the values for the user.
//set-up object to use the web.config file
string connectionString = WebConfigurationManager.ConnectionStrings["QSISConnection"].ConnectionString;
//set-up connection object called 'myConnection'
SqlConnection myConnection = new SqlConnection(connectionString);
// open database communication
myConnection.Open();
// create the SQL statement
string query = "SELECT ModuleAssessmentUser.ModuleID, ModuleAssessmentUser.AssessmentID, MarkPercentage * Assessment.AssessmentWeighting AS FinalMark FROM ModuleAssessmentUser INNER JOIN[Assessment] ON(Assessment.AssessmentID = ModuleAssessmentUser.AssessmentID) WHERE (ModuleAssessmentUser.UserID = 2)";
// set-up SQL command and use the SQL and myConnection object
SqlCommand myCommand = new SqlCommand(query, myConnection);
// create a SqlDataReader object that asks for data from a table
SqlDataReader rdr = myCommand.ExecuteReader();
// create variable to add column values
int totalmark = 0;
// when in read mode ask for data
while (rdr.Read())
{
// put variable value from moduleID column in local variable
string usermodule = rdr["ModuleID"].ToString();
// needs to be a text control called 'moduleid' on the aspx web page
modulenumber.Text = usermodule.ToString();
// get value of your weighting
int fmark = Convert.ToInt32(rdr["FinalMark"]);
// update the moduleweighting variable by adding the value in the column FinalMark
// this is in a loop so should accumulate the values
totalmark = totalmark + fmark;
result.Text = totalmark.ToString();
}
// once the adding up has been added up display total in final text box
// create a text control on aspx called 'result'
// need to convert int to string to display in text control
myConnection.Close();
I am still quite new to C# and ASP.NET, so any advice is appreciated.
Thanks in advance
Try code below :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//set-up object to use the web.config file
string connectionString = WebConfigurationManager.ConnectionStrings["QSISConnection"].ConnectionString;
//set-up connection object called 'myConnection'
SqlConnection myConnection = new SqlConnection(connectionString);
// open database communication
myConnection.Open();
//create the SQL statement
string query = "SELECT ModuleAssessmentUser.ModuleID, ModuleAssessmentUser.AssessmentID, MarkPercentage * Assessment.AssessmentWeighting AS FinalMark FROM ModuleAssessmentUser INNER JOIN[Assessment] ON(Assessment.AssessmentID = ModuleAssessmentUser.AssessmentID) WHERE (ModuleAssessmentUser.UserID = 2)";
//set-up SQL command and use the SQL and myConnection object
SqlCommand myCommand = new SqlCommand(query, myConnection);
//create a sqldatareader object that asks for dats from a table
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
int markPercentage = dt.AsEnumerable().Sum(x => x.Field<int>("MarkPercentage"));
}
}
}
I want to display information of user stored in a MS Access database. The user enters his userid and on clicking a button following function is called. But no data is being displayed. What am I doing wrong ?
System.Data.OleDb.OleDbConnection con;
System.Data.OleDb.OleDbDataAdapter da;
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
con.Close();
}
You need to call GridView1.DataBind()
GridView1.DataSource = t;
GridView1.DataBind();
Just a side-note, it is good practice to wrap your connection with using
using(con = new System.Data.OleDb.OleDbConnection())
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
...
...
}
This ensures your connection is properly disposed after use
You should use bind function:
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
GridView1.DataBind();
con.Close();
}
First off, please, please please don't concatenate your WHERE parameters in your SQL. Use Parameters. Second, Add a "using System.Data.OleDb" statement at the top of your module, so that you are not having to type things like:
System.Data.OleDb.OleDbDataAdapter
Over and over again.
Try the following code. Personally, when I have to work with data tables and such, I prefer to avoid all the DataAdapter nonsense, and keep it as simple as possible.
Note in the code below:
the "using" blocks. These place the variables created within them inside their own scope, and take care of disposal and such for you.
I used an OleDb Parameter instead of concatenating criteria. This is a much safer way to do things, and creates much cleaner and more readable code as well, especially in cases where you have several criteria in your WHERE clause.
I assume your UserID input is a string, since you are grabbing the value from a Textbox. If it is in fact an int value (such as an auto-incrementing id in MS Access) you will need to use an int data type instead. You may have to mess with it a little. When you are still figuring this stuff out, it can be a bit painful. However, using parameters increases security and maintainability.
Once you have obtained a data table as the return from the MyUsers method, you should be able to simply set the data source of your Gridview. If you have difficulties still, do as Steve suggests and check the Autogenerate columns property in the designer, or set it in code.
Not that I have moved the connection string to the project Properties/Settings. You should find this in the solution designer. Place your connection string there, in one spot, and you can obtain it from anywhere in your code. If you later change the connection string (such as moving your Db to another computer, server share, etc) you need only change it in one place.
SAMPLE CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; // put this here, and stop writing long namespaces inline
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Where possible, move code out of specific event handlers
// into methods which can be re-used from other client code.
// Here, I pulled the actual data access out into separate methods,
// and simply call it from the event handler:
this.LoadGridView(textBox1.Text);
}
private void LoadGridView(string UserID)
{
// Now we can load the gridview from other places in our
// code if needed:
this.dataGridView1.DataSource = this.MyUsers(UserID);
}
private DataTable MyUsers(string UserID)
{
var dt = new DataTable();
// Use a SQL Paramenter instead of concatenating criteria:
string SQL = "SELECT * FROM Leave WHERE userid = #UserID";
// The "using" statement limits the scope of the connection and command variables, and handles disposal
// of resources. Also note, the connection string is obtained from the project properties file:
using(OleDbConnection cn = new OleDbConnection(Properties.Settings.Default.MyConnectionString))
{
using (var cmd = new OleDbCommand(SQL, cn))
{
// For simpler things, you can use the "AddWithValue" method to initialize a new parameter,
// add it to the Parameters collection of the OleDBCommand object, and set the value:
cmd.Parameters.AddWithValue("#UserID", UserID);
// Get in, get out, get done:
cn.Open();
dt.Load(cmd.ExecuteReader());
cn.Close();
}
}
return dt;
}
}
}
Hope that helps. It's not how everyone might do it, but I have found it provides maximum flexibility, when you must work with MS Access.
Guys I searched around like hell but nothing could help me so I think it's time to ask. Before I write to problem, I need to say that I need it's solution asap because it's a project that I have to give tomorrow and I stuck on the same subject since ages and still losing time.
OK here it is;
I need to add a book to a library system, at first phase I add the standard book features which has only "one value" like (name, page number, publishing time, publisherID etc) but as wanted by me book MAY HAVE MULTIPLE WRITERS AND CATEGORIES which killed me and still I can't resolve. I tried to add book to it's (books) table then with the information i got from that i did an other insert op. to (bookWriters) table. While I check it, compiler does everything in order without error but when I check table from SQL Server there is nothing.
Here is what I tried to do;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace Project_
{
public partial class addBook: Form
{
public addBook()
{
InitializeComponent();
}
public main refForm;
int chosenWritersNumber; //how many writers have selected on listbox
int[] writers= { }; // an array list that i keep writerIDs that comes from class
int ind = 0;
int insertedBookID; // to catch latest added book's ID
int chosenWriterID; // writer that will be added
private void bookAddingPreps()
{
chosenWritersNumber = lstWriters.SelectedItems.Count;
Array.Resize<int>(ref writers, chosenWritersNumber );
for (int i = 0; i < chosenWritersNumber ; i++)
{
writers[i] = ((X_Writers)lstWriters.SelectedItems[i]).XWriterID;
}
}
private void addMainBookInfos()
{
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("AddBook", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookISBN", txtISBN.Text);
con.Close();
}
private void catchAddedBookID()
{
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("catchBookID", con);
com.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
insertedBookID = dr.GetInt32(0);
}
}
dr.Close();
con.Close();
}
private void addWritersOfTheBook()
{
chosenWriterID = writers[ind];
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("addBookWriters", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookID", insertedBookID);
com.Parameters.AddWithValue("#WriterID", chosenWriterID);
con.Close();
}
I call these methods on click of a button. You see also stored procedure names but as I checked they all correct, there must be a mistake in this page that I still cant see but if it's needed I can add what procedures writes but they all tested and seems working.
So as i said, when i do this, as ind = 0, a writer should have been added, break point shows everything is ok and compiler doesnt show any errors but when I check sql server table, its empty.
Written in C# with using Visual Studio 2010 Ultimate and SQL Server 2008 Dev.
Thanks
You forget to execute your SqlCommand's. Make a call to command.ExecuteNonReader(); to execute it without expecting any results. see: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
Apart form that, dont forget to dispose the resources acquired in your methods. Something like:
private void addMainBookInfos()
{
using (SqlConnection con = new SqlConnection(Conn.Activated))
using (SqlCommand com = new SqlCommand("AddBook", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookISBN", txtISBN.Text);
com.ExecuteNonQuery()
// close can be omitted since you are already using the 'using' statement which automatically closes the connection
con.Close();
}
}
How can we insert the values of datatable in SQL using c#? And the second question is how we can copy the SQL table into datatable variable?
UPDATE: One thing this answer didn't have in the past is links to information for SQL and database newbies, so I will put some relevant links here as well so that you (or anyone else) can brush up on their SQL and other database design skills.
W3 Schools SQL Tutorial
Database Design Tutorial
UPDATE 2: Here is an example of filling a datatable:
//Namespace References
using System.Data;
using System.Data.SqlClient
/// <summary>
/// Returns a DataTable, based on the command passed
/// </summary>
/// <param name="cmd">
/// the SqlCommand object we wish to execute
/// </param>
/// <returns>
/// a DataTable populated with the data
/// specified in the SqlCommand object
/// </returns>
/// <remarks></remarks>
public static DataTable GetDataTable(SqlCommand cmd)
{
try
{
// create a new data adapter based on the specified query.
SqlDataAdapter da = new SqlDataAdapter();
//set the SelectCommand of the adapter
da.SelectCommand = cmd;
// create a new DataTable
DataTable dtGet = new DataTable();
//fill the DataTable
da.Fill(dtGet);
//return the DataTable
return dtGet;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
A lot of this is taken from another answer I have written previously, but it goes into detail about your exact issues:
Original Answer:
This sounds like you more or less need a basic introduction to connecting and manipulating a database from C#. The above poster said to look into LINQ to SQL, but you can also look into the more basic underlying framework of ADO.NET which will get you to understand the basics of how it works.
Also, you can use this site right here for a number of different database tutorials for C#.
Edit: More information from C# Station, CodeProject, and Codersource
Edit 2: If you are interested in things like Linq to SQL as others have mentioned above, here are some tutorials from C# Corner, and C-Sharp Online
Edit 3: Others would also suggest things such as the ADO.NET Entity Framework. I would not necessarily suggest this for beginners who still need to grasp the fundamentals of working with a database. Here is some information from the MSDN Overview
Simple Example (This is pulled directly from the C# Station link given above)
Listing 1. Using a SqlConnection
using System;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Demonstrates how to work with SqlConnection objects
/// </summary>
class SqlConnectionDemo
{
static void Main()
{
// 1. Instantiate the connection
SqlConnection conn = new SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;
Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
// 2. Open the connection
conn.Open();
// 3. Pass the connection to a command object
SqlCommand cmd =
new SqlCommand("select * from Customers", conn);
//
// 4. Use the connection
//
// get query results
rdr = cmd.ExecuteReader();
// print the CustomerID of each record
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
conn.Close();
}
}
}
}
For both of these, you want a relevant data adapter, e.g. SqlDataAdapter.
I suggest you find a good ADO.NET book or tutorial - it's bound to be in there. Alternatively, there are MSDN articles on DataAdapters/DataReaders and Retrieving and Modifying Data in ADO.NET.
I would read up on ADO.NET and LINQ to SQL for starters.