I am using SQl CLR for parsing some table column. I want to execute the queries also in C# user defined function. Can somebody give an example to execute select and insert queries in the function?
Thank you in advance.
SqlConnection objSqlConn;
string connString = string.Empty;
connString = "Data Source=(local);Initial Catalog=DB;User ID=uname;pwd=pass;Password=pass";
objSqlConn = new SqlConnection(connString);
objSqlConn.Open();
string query = "Select count(*) FROM [DB].[dbo].[TableName]";
SqlCommand cmdTotalCount = new SqlCommand(query, objSqlConn);
cmdTotalCount.CommandTimeout = 0;
string TotalCountValue = cmdTotalCount.ExecuteScalar().ToString();
return TotalCountValue;
In CLR, you can use existing connection to run queries.
Simple, returning data to client:
var cmd = new SqlCommand("select * from [table]");
SqlContext.Pipe.ExecuteAndSend(cmd);
Returning data via SqlDataReader:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("select * from table", con);
con.Open();
var rdr = cmd.ExecuteReader();
SqlContext.Pipe.Send(rdr);
rdr.Close();
con.Close();
Running other commands:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("insert into [table] values ('ahoj')", con);
con.Open();
var rsa = cmd.ExecuteNonQuery();
con.Close();
Once you switch to C# you execute queries like you'd normally do from your application (using ADO.NET's SqlConnection and SqlDataReader, using LINQ to SQL or using your custom build data layer).
To connect with the database you have to mention the database username and password in the connection string of your web.config file.
Related
I am trying to get the name of the employee from the database and fill it in the textbox for the respective employee id.
I tried this code but nothing is happening on the page. It just reloads and the textbox (name) is left blank only.
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-0FUUV7B\SQLEXPRESS;Initial Catalog=EmployeeDetails;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from ProfessionalDetails where EmpId='"+EmployeeId.Text+"'", con);
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
Name.Text = da.GetValue(1).ToString();
}
con.Close();
Better solution is to execute the sql statement through Parameterized value.
The details of that process is given below:
using (SqlConnection con = new SqlConnection(live_connectionString))
{
using (SqlCommand cmd = new SqlCommand("Query", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmpId", employeeId);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
var ds = new DataSet();
da.Fill(ds);
string? name = ds.Tables[0].Rows[1]["Variable name"].ToString();
Name.Text =name;
};
}
}
As mentioned above in comments, you have lot of issues.
you should use using with the connection to dispose of them.
You should use parameterized queries to avoid SQL injection.
Put your code in try catch so that you can easily identify the root cause of the issue.
Define the connection string in config file three than defining in the c# code.
You don’t need to select all the columns. And please avoid select * in the query, instead just write your column name, as you want to select only one column here.
You can use ExecuteScalar, it’s used when you are expecting single value.
And first make sure that textbox has the expected value when you are calling this query.
As noted, use paramters, and BETTER use STRONG typed paramters.
And no need to use a dataset, this is a single table - so use a datatable.
thus:
string strSQL =
#"select * from ProfessionalDetails where EmpId= #ID";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
con.Open();
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = EmployeeID.Text;
DataTable rstData = new DataTable();
rstData.Load(cmd.ExecuteReader());
if (rstData.Rows.Count > 0)
Name.Text = rstData.Rows[0]["Name"].ToString();
}
}
For reference, this page (add.ashx.cs), is an add page to a database.
What I'm trying to do is :
figure out how to execute string queryID, and then
store the results of queryID
I'm a bit new at this, but this is what I'm working with so far. Am I on the right path, and what should I change? I don't believe the code below includes storing the results, but just executing queryID.
// new query to get last ID value
// store the command.executeNonQuery results into a variable
string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
// first: look up how to execute queryID
// then: store results of query ^
// execute queryID? (section below)
SqlConnection sqlConnection1 = new SqlConnection(queryID);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * FROM queryID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// data is accessible through the datareader object here
sqlConnection1.Close();
There are some things missmatched in your code sample. First queryID is your actual query. Second in SqlConnection you need to provide a connection string, that connects to your database (SQL Server, ACCESS, ...). A valid example could look like this:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
SqlDataReader reader;
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
List<string> results = new List<string>();
if(reader.HasRows)
{
while(reader.Read())
{
results.Add(reader[0].ToString());
}
}
sqlConnection1.Close();
Another thing is, that you execute a reader but only select one single value. You can perfectly use ExecuteScalar for that:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
sqlConnection1.Close();
One last thing. You should use objects that implement IDisposable in a using block. This way the will be removed from memory when they are no longer needed:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
}
I got this OfficeWriter error when debugging the console application. I used methods to retrieve config details for the database used in the coding from the master database, and ended up having this error.
Error binding in GetColumnNumber at row 1
Attached here is partial coding for my work. Anyone can explain me what the error is?
SqlDataReader rdSource = getSource();
SqlDataReader rdDestination = getDestination();
SqlDataReader rdCode = getCode();
while (rdSource.Read() && rdDestination.Read())
{
string src = rdSource["Value"].ToString();
string dest = rdDest["Value"].ToString();
ExcelTemplate XLT = new ExcelTemplate();
XLT.Open(src);
DataBindingProperties dataProps = XLT.CreateBindingProperties();
XLT.BindData(rdCode, "Code", dataProps);
XLT.Process();
XLT.Save(dest);
}
//rdCode method
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
while (rdConnection.Read())
{
string con = rdConnection["Value"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
string SQL = "SELECT * FROM Sales.Currency";
sqlCon.Open();
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader();
sqlCon.Close();
}
return rdConnection;
//getConnection method
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string cSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = 'Data Source=localhost;Initial Catalog=Test;Integrated Security=True'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
//getSource & getDestination methods
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string srcPath = #"FILE PATH NAME"; //change to destPath for getDestination
string sSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = '" + srcPath + "'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
The error is a generic message that is thrown by ExcelWriter when it is unable to bind data to the template.
I think this might be caused by your getCode() method. In getCode(), you use a SQLDataReader to retrieve the connection string for the database:
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
Then you execute a SQL query against that database, but you don't actually get a handle on the SqlDataReader that is executing the SQL query to return the data.
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader(); //Note: This returns the SqlDataReader that contains the data
Then you return rdConnection, which is the SQLDataReader for the connection string - not the data you are trying to import. rdConnection contained 1 row and you already called Read(), so there are no records left to read.
SqlDataReader rdCode = getCode();
...
XLT.BindData(rdCode, "Code", dataProps);
The SQL reader you are binding is the used 'connection string', rather than your sales data. I would recommend the following:
Return the new SqlDataReader that is generated by cmd.ExecuteReader() in getCode(), rather than rdConnection.
Do not close the connection to this new SqlDataReader. ExcelWriter needs to be able to read the data reader in order to bind the data. If you close the connection, ExcelWriter will not be able to bind data correctly.
I am trying to execute a SQL statement with a where clause which looks like
string s2 = "Select * from idtyfile where oysterid=" + id ;
SqlCommand da2 = new SqlCommand(s2, con); or
SqlAdapter da2 = new SqlAdapter(s2, con);
Both of these are failing when I am trying to execute them
da2.ExecuteReader();
the data in ID looks like
ID
43PCOU5T
ZP6RAEJ0
For some reason both of these queries are failing on these kind of data.
You are missing the single quotes in your select command which is what is making your original SELECT fail. However I would like to note that you should always parameterize and encapsulate your SqlCommand / SqlConnection in a using statement. The following would be a cleaner more secure way to solve your problem.
string s2 = "Select * from idtyfile where oysterid=#id";
DataTable myDataTable = new DataTable();
using (SqlConnection conn = new SqlConnection(myConnectionString))
using (SqlCommand cmd = new SqlCommand(s2, conn))
{
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
myDataTable.Load(cmd.ExecuteReader());
}
For some educational resources, you should look at the following links.
MSDN Reference for the using keyword
MSDN Reference for SqlCommand -- Look at the Parameters property.
When I try to select values from a local database it executes without any issue. But when I try to insert and delete it's executing the query but it's not affecting any rows.
This is the code I'm using to delete row from my local database:
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = Database1.sdf";
SqlCeCommand cmd = sqlConnection1.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "DELETE FROM table1 WHERE slno=2";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.Prepare();
int aff=cmd.ExecuteNonQuery();//here its returning '0'
MessageBox.Show(aff.ToString());
sqlConnection1.Dispose();
sqlConnection1.Close();
It is possible that the delete won't affect any rows.
As an aside, I would advise using the using statement in your code:
using (SqlCeConnection conn = new SqlCeConnection("Data Source = Database1.sdf"))
using (SqlCeCommand comm = new SqlCeCommand("DELETE FROM table1 WHERE slno = 2", conn))
{
conn.Open();
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
This will handle disposal of relevant objects for you.
Assuming that the SQL is relevant to your database and that you have successfully connected using the connection string beforehand, then the above could will perform a delete action against your database.