Nothing happens on query execution - c#

I have this simple code C# and SQL Server database:
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
// here like cursor stop
cm2.ExecuteNonQuery();
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
I have run it but nothing happens on query execution I used MessageBox like that to identify the line that has the problem
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
MessageBox.Show("1");
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
MessageBox.Show("2");
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
MessageBox.Show("3");
// here cursor stops
cm2.ExecuteNonQuery();
// that messagebox isn't shown
MessageBox.Show("4");
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
Any help will be appreciated

You haven't opened your Connection. See below.
You should also use the using syntax to make use of IDisposable
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
var sqlCmdText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
try
{
using (var sqlConnection = new SqlConnection([YOUR CONNECTION STRING HERE]))
{
using (var sqlCommand = new SqlCommand(sqlCmdText, sqlConnection))
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new DataException(ex.Message);
}

Related

Issue with Open DataReader which must be closed first

I am getting the following error in my code:
"There is already an open DataReader associated with this Command
which must be closed first."
I have two SqlDataReaders and I made sure that I closed the first one after loading the DataViewGrid.
Below is the function that is giving me the issue. I marked the line that is throwing the error. I've tried variations with 'try' and 'using', I've tried to rename diff SqlConnections, SqlDataReaders and SqlCommands. I am at a loss here.
Can I not have an open SqlDataReader and SqlCommand open at the same time on one connection?
private void ApprovedTransferAction(int rowNum) {
bool foundFlag = false;
//int XferQty = (int)gridData.Rows[rowNum].Cells["FinalQty"].Value;
string PorgID = "";
using (SqlConnection conn = new SqlConnection(Global.connString)) {
conn.Open();
// Locate id in PorgReqs
string sqlSelectQuery = "SELECT id FROM PorgReqs WHERE location_id = #NewLocationID AND vendor_id = #VendorID AND item_id = #Item";
using (SqlCommand sqlSelect = new SqlCommand(sqlSelectQuery, conn)) {
sqlSelect.Parameters.Add("#NewLocationID", SqlDbType.VarChar, 60).Value = gridData.Rows[rowNum].Cells["NewLocation"].Value;
sqlSelect.Parameters.Add("#VendorID", SqlDbType.VarChar, 60).Value = gridData.Rows[rowNum].Cells["Vendor"].Value;
sqlSelect.Parameters.Add("#Item", SqlDbType.VarChar, 60).Value = gridData.Rows[rowNum].Cells["Item"].Value;
using (SqlDataReader sqlDataReader2 = sqlSelect.ExecuteReader()) {
// If Item is found at Target Location; FinalQty of Source Added to AddlQty of Target
if (sqlDataReader2.HasRows) {
sqlDataReader2.Read();
PorgID = Convert.ToString(sqlDataReader2["id"]);
MessageBox.Show("Found ID: " + PorgID);
string sqlUpdateQuery = "UPDATE PorgReqs SET AddlQty += #XferQty WHERE id = #ID";
using (SqlCommand sqlUpdate = new SqlCommand(sqlUpdateQuery, conn)) {
sqlUpdate.Parameters.Add("#XferQty", SqlDbType.Int).Value = (int)gridData.Rows[rowNum].Cells["FinalQty"].Value;
sqlUpdate.Parameters.Add("#ID", SqlDbType.Int).Value = sqlDataReader2["id"];
sqlUpdate.CommandType = CommandType.Text;
sqlUpdate.ExecuteNonQuery();
} // End sqlUpdate Command
} else { // Item was not found at Target location
string sqlUpdateQuery = "UPDATE PorgReqs SET " +
" location_id = #TargetLoc, " +
" requirement_location_id = #TargetLoc, " +
" ship_to_location_id = #TargetLoc " +
" WHERE " +
" location_id = #SourceLoc AND " +
" vendor_id = #VendorID AND " +
" item_id = #Item";
using (SqlCommand sqlUpdate = new SqlCommand(sqlUpdateQuery, conn)) {
sqlUpdate.Parameters.Add("#TargetLoc", SqlDbType.Int).Value = gridData.Rows[rowNum].Cells["NewLocation"].Value;
sqlUpdate.Parameters.Add("#SourceLoc", SqlDbType.Int).Value = gridData.Rows[rowNum].Cells["Location"].Value;
sqlUpdate.Parameters.Add("#VendorID", SqlDbType.Int).Value = gridData.Rows[rowNum].Cells["Vendor"].Value;
sqlUpdate.Parameters.Add("#Item", SqlDbType.VarChar, 60).Value = gridData.Rows[rowNum].Cells["Item"].Value;
sqlUpdate.CommandType = CommandType.Text;
sqlUpdate.ExecuteNonQuery(); // ERROR HERE
} // End sqlUpdate Command
} // End Else
sqlDataReader2.Close();
}
/*} catch (Exception ex) {
Console.WriteLine(ex.Message);
MessageBox.Show("Try SQLReader: " + ex.Message);
} */
} // End sqlSelect Command
} // End SQL Connection
// See if id exists in grid
MessageBox.Show("Checking Grid");
foreach (DataGridViewRow row in gridData.Rows) {
if (foundFlag == true)
break;
else if (row.Cells["id"].Value.ToString() == PorgID) {
// Update grid
row.Cells["AddlQty"].Value = Convert.ToInt32(gridData.Rows[rowNum].Cells["FinalQty"].Value) + Convert.ToInt32(row.Cells["AddlQty"].Value);
row.Cells["FinalQty"].Value = Convert.ToInt32(row.Cells["RecQty"].Value) + Convert.ToInt32(row.Cells["AddlQty"].Value);
foundFlag = true;
MessageBox.Show("Found: " + foundFlag);
} // End If
} // End ForEach
// Remove the Row from the Grid
gridData.Rows.RemoveAt(rowNum);
}
Just add MultipleActiveResultSets=true to your connection string.

c# Connection must be valid and open to commit transaction TransactionScope

I'm using Transactions on my Dao and in particular I'm using the TransactionScope object for the first time. But when I compile and start my procedure on my pc the method I wrote in will give me this error:
Connection must be valid and open to commit transaction
code:
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (TransactionScope scope = new TransactionScope())
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteReader();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
//cmd.Transaction = Transazione;
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteReader();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}
You need to move scope.Complete(); within your connection using as it is being disposed before you are completing your scope. Also, change your calls to use ExecuteNonQuery as opposed to ExecuteReader, as you are opening a SqlDataReader and not disposing of it.
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteNonQuery();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteNonQuery();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
ok Ok i have inverted using connection with scope
And I opened the connection before scope and works !
I hope it is right, thank you !
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
using (TransactionScope scope = new TransactionScope())
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteNonQuery();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteNonQuery();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}

C# : There is already an open DataReader associated with this Command which must be closed first

String sql = "SELECT * from mybrknElements; ";
String sql2 = "";
String sWord = "" ;
String sNum = "" ;
int nWords = 0;
cnn.Close();
cnn.Open();
SqlCommand command = new SqlCommand(sql, cnn);
cnn2.Close();
cnn2.Open();
SqlDataReader drb;
drb = command.ExecuteReader();
while (drb.Read())
{
sNum = drb["ID"].ToString();
sWord = drb["Element"].ToString();
MessageBox.Show("OUTER loooop sNum = " + sNum + " sWord = " + sWord);
sql2 = "SELECT * from mybrknElements2; ";
String sWord2 = "" ;
String sNum2 = "";
SqlCommand command22 = new SqlCommand(sql2, cnn2);
SqlDataReader drcc;
drcc = command22.ExecuteReader(); //ERROR comes up after this line
while (drcc.Read())
{
sNum2 = drcc["ID"].ToString();
sWord2 = drcc["Element"].ToString();
if (Equals(sWord2,sWord2))
{
nWords = nWords + 1;
MessageBox.Show("sNum2 = " + sNum2 + " sWord2 = " + sWord2);
}
}
//---check occurances--------------
}
Above is my code : I have used 2 SqlDataReaders ,one within other
I get the error at the end of the while loop
: There is already an open DataReader associated with this Command which must be closed first
Can someone please help?
Thank you.
You should stop reusing your command and connection objects, and dispose of them properly once they have been used. There is no advantage to reusing the objects (.NET will reusing open sockets to the database through connection pooling anyway, even for difference connection objects), and it only causes issues like this.
So without reusing objects, and disposing of the ones you correctly your code might end up something like:
string sql = "SELECT ID, Element FROM mybrknElements; ";
string sql2 = "SELECT ID, Element FROM mybrknElements2;";
int nWords = 0;
string connectionString = "Your Connection String";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql1, connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
{
string sWord = reader.GetString(0);
string sNum = reader.GetString(1);
using (var connection2 = new SqlConnection(connectionString))
using (var command2 = new SqlCommand(sql2, connection2))
{
connection2.Open();
using (var reader2 = command2.ExecuteReader())
{
string sWord2 = reader2.GetString(0);
string sNum2 = reader2.GetString(1);
if (Equals(sWord1,sWord2))
{
nWords++;
}
}
}
}
}
N.B. In each data reader you only use two columns, so I have added these columns to the select list in each SQL statement so that you are not unnecessarily retrieving data that will never be used.
The whole loop strikes me as pointless and inefficient though, assuming the whole purpose is to get nWords with the correct number, you can do this all in SQL:
SELECT nWords = COUNT(*)
FROM mybrknElements AS e
INNER JOIN mybrknElements AS e2
ON e2.ID = e.ID;
Try this code,
SqlDataReader drb;
drb = command.ExecuteReader();
while (drb.Read())
{
sNum = drb["ID"].ToString();
sWord = drb["Element"].ToString();
MessageBox.Show("OUTER loooop sNum = " + sNum + " sWord = " + sWord);
sql2 = "SELECT * from mybrknElements2; ";
String sWord2 = "" ;
String sNum2 = "";
SqlCommand command22 = new SqlCommand(sql2, cnn2);
SqlDataReader drcc;
drcc = command22.ExecuteReader(); //ERROR comes up after this line
drb.Close();
while (drcc.Read())
{
sNum2 = drcc["ID"].ToString();
sWord2 = drcc["Element"].ToString();
if (Equals(sWord2,sWord2))
{
nWords = nWords + 1;
MessageBox.Show("sNum2 = " + sNum2 + " sWord2 = " + sWord2);
}
}
drcc.Close();
}

Input string was not in a correct format in Sales Order

I am having this problem
Input string was not in a correct format.
highlighted to the part of:
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
I am having a hard time figuring out what is the error, can you help me? Thank you very much.
Here is my set codes:
private void displayNavigate()
{
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
double dTotal = 0;
try
{
for (int nRow = 0; nRow <= grdDetails.Rows.Count - 1; nRow++)
{
dTotal = dTotal + Convert.ToDouble((grdDetails.Rows[nRow].Cells["Amount"].Value.ToString()));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
lblTotal.Text = string.Format("{0:#,##00.00}", dTotal);
}
//================================================================================
//================================================================================
private void DisplayOrder(int nOrderNo)
{
try
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText = "SELECT " +
"B.OrderNo, B.OrderDate, A.CustomerNo, " +
"A.CustomerName, A.CustomerAddress, B.PurchaseOrderNo, B.AgentName, B.Status " +
"FROM Customers AS A, Orders AS B " +
"WHERE A.CustomerNo = B.CustomerNo " +
"AND B.OrderNo ='" + nOrderNo + "'";
SqlDataReader dr = cmdSelect.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
txtOrderNo.Text = dr["OrderNo"].ToString();
dtpOrderDate.Value = Convert.ToDateTime(dr["OrderDate"].ToString());
txtCustomerNo.Text = dr["CustomerNo"].ToString();
txtCustomerName.Text = dr["CustomerName"].ToString();
txtCustomerAddress.Text = dr["CustomerAddress"].ToString();
txtPONo.Text = dr["PurchaseOrderNo"].ToString();
cboAgentName.Text = dr["AgentName"].ToString();
txtOrderStatus.Text = dr["Status"].ToString();
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//================================================================================
//================================================================================
private void DisplayOrderDetails(int nOrderNo)
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText =
"SELECT PackagingOutside, Quantity, Unit, ProductNo, ProductName, ProductSize, PackagingInside, " +
"SellingDiscount, SellingPrice, Amount FROM OrderDetails WHERE OrderNo = '"
+ nOrderNo + "'";
SqlDataAdapter daDetail = new SqlDataAdapter();
daDetail.SelectCommand = cmdSelect;
DataSet ds = new DataSet();
daDetail.Fill(ds, "OrderDetails");
grdDetails.DataSource = null;
grdDetails.DataSource = ds.Tables["OrderDetails"];
}
when you use Convert.ToInt16 you will get this exception if value does not consist of an optional sign followed by a sequence of digits (0 through 9)
Do a validation for inputs before proceed like below.
int orderNo;
if (int.TryParse(txtOrderNo.Text, out orderNo))
{
DisplayOrder(orderNo);
DisplayOrderDetails(orderNo);
}
Side Note :
don't share the SqlConnection create new instant when you need it and wrap it with using block like below
using (SqlConnection con = new SqlConnection(connectionString))
{
}
Use SQL Parameters
cmdSelect.CommandText = "SELECT * FROM Orders WHERE OrderNo = #OrderNo";
cmdSelect.Parameters.AddWithValue("#OrderNo", nOrderNo);
This means that the value in txtOrderNo.Text is not considered an integer. You will get this error if your textbox is empty.
Either check that the textbox contains data, or use the TryParse (http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method
There are two things to consider,
Values entered in the textbox should be an integer in the range of 16 bit, if it can be bigger value, then you have to think of going to long, int32 etc.
Validate the textbox using TryParse() which will tell you whether it has valid value entered.

Generate database creation scripts

Is it possible to generate the database creation scripts for a SQL server database from .NET?
I am using C# and I would like to create some sort of an installer project for my application
on which I can select an existing database, generate the creation scripts and run them on another SQL server instance.
Yes, it is possible.
It's easy to do this with SMO, see Transfer class for scripting operations and Database class for database operations (create, drop, etc). Usage looks like this:
private StringCollection GetTransferScript(Database database)
{
var transfer = new Transfer(database);
transfer.CopyAllObjects = true;
transfer.CopyAllSynonyms = true;
transfer.CopyData = false;
// additional options
transfer.Options.WithDependencies = true;
transfer.Options.DriAll = true;
transfer.Options.Triggers = true;
transfer.Options.Indexes = true;
transfer.Options.SchemaQualifyForeignKeysReferences = true;
transfer.Options.ExtendedProperties = true;
transfer.Options.IncludeDatabaseRoleMemberships = true;
transfer.Options.Permissions = true;
transfer.PreserveDbo = true;
// generates script
return transfer.ScriptTransfer();
}
if you want to create database dynamically with c# code then here is the code:
you can do it like this also:
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
bool resultdbexistencx = CCMMUtility.CheckDatabaseExists(con, txt_DbName.Text);
if (!resultdbexistencx)
{
// if not exists create it check the user name for sub-admin avialibe or not.
if (txt_DbName.Text.Trim() == string.Empty) return;
string strDbCreate;
strDbCreate = "CREATE DATABASE " + txt_DbName.Text + " ON PRIMARY " +
"(NAME = " + txt_DbName.Text + "_Data, " +
"FILENAME = 'D:\\" + txt_DbName.Text + "Data.mdf', " +
"SIZE = 4MB, MAXSIZE = 10GB, FILEGROWTH = 100%) " +
"LOG ON (NAME = " + txt_DbName.Text + "_Log, " +
"FILENAME = 'D:\\" + txt_DbName.Text + ".ldf', " +
"SIZE = 4MB, " +
"MAXSIZE = 10GB, " +
"FILEGROWTH = 100%)";
SqlConnection sqlconn = new SqlConnection(Connectionstring);
SqlCommand cmd = new SqlCommand(strDbCreate, sqlconn);
try
{
sqlconn.Open();
sqlconn.ChangeDatabase("master");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Int32 dbRollbackResult = RollBackTheWholetransaction(txt_DbName.Text.Trim(), Convert.ToInt32(HospitalResult));
if (dbRollbackResult == 1)
{
Response.Write(ex.Message);
lblMessage.DisplayMessage(StatusMessages.ErrorMessage, "There is some problem while generating the database or database name doesn't avialible.");
}
}
Here is the code of "RollBackTheWholetransaction" method :
private Int32 RollBackTheWholetransaction(String DbName, Int32 HospitalId)
{
Int32 result = 0;
try
{
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
String sqlCommandText = "ALTER DATABASE [" + DbName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
String sqlCommandText1 = "DROP DATABASE [" + DbName + "]";
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
ClsHospitals objHospiitals = new ClsHospitals();
String resultDbdelete = objHospiitals.DeleteHospital(HospitalId, Session["devSuperAdmin"].ToString());
if (resultDbdelete == "1")
{
result = 1;
}
else
{
result = 2;
}
}
else
{
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
}
con.Close();
con.Dispose();
result = 1;
}
catch (Exception ex)
{
result = 0;
}
return result;
}
And here is the code to check existence of db in Database :
public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
// tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
if (tmpConn.State == System.Data.ConnectionState.Open)
{
tmpConn.Close();
tmpConn.Dispose();
}
tmpConn.Open();
tmpConn.ChangeDatabase("master");
int databaseID = (int)sqlCmd.ExecuteScalar();
tmpConn.Close();
result = (databaseID > 0);
}
}
}
catch (Exception ex)
{
result = false;
}
return result;
}
its the working code, hope it will work for you too....
You have to create your own installer by coding it all yourself. there are frameworks out there that make it much easyier.
like Windows Installer XML (WiX)
Windows installer
and more...
I would suggest you to have a look at WiX, worked with it and its quite easy and you can do much. Can be integrated in Visual Studio

Categories