Generate database creation scripts - c#

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

Related

Nothing happens on query execution

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);
}

How to create new database upon reopening application?

I have a log viewing application that writes log statements to a database and then sends them from the database to the log viewer GUI. I want to be able to open more than one instance of the log viewer but when I do it will be creating a database with the same name as the previous instance of the viewer. I've tried creating a database with a different name if one has already been created but that doesn't seem to work. Any suggestions? Here's the code for creating/accessing/destroying databases:
public class Database
{
public bool hasAdminPriv
{
get;
set;
}
public bool hasBeenCreated
{
get;
set;
}
public Database()
{
hasAdminPriv = true;
//Construction checks to see if user has Admin priveleges
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!isElevated)
hasAdminPriv = false;
}
//returns true if the database creation was successful
public bool CreateDatabase()//creates a database dynamically by making a query request to the server
{
String str;
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=Master;Integrated Security=True");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseData.mdf', " +
"SIZE = 30MB, MAXSIZE = 10GB, FILEGROWTH = 20%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseLog.ldf', " +
"SIZE = 10MB, " +
"MAXSIZE = 1GB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
int done = 0;
while (done < 10)
{
String str2 = "CREATE DATABASE" + done + " MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseData.mdf', " +
"SIZE = 30MB, MAXSIZE = 10GB, FILEGROWTH = 20%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseLog.ldf', " +
"SIZE = 10MB, " +
"MAXSIZE = 1GB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand2 = new SqlCommand(str2, myConn);
try{
myCommand2.ExecuteNonQuery();
}
catch{
++done;
}
myConn.Close();
hasBeenCreated = true;
return true;
}
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
hasBeenCreated = true;
return true;
}
//Creates the table in the database by a query request
//a return value of true means Database was created succesfully
public bool CreateTable()
{
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=MyDatabase;Integrated Security=True");
string createString = "CREATE TABLE storage (ID INT NOT NULL, Level varchar(255) , LevelInt INT, DateTime varchar(255),Counter smallint,Device varchar(255), Source varchar(255), Description varchar(255),PRIMARY KEY (ID))"; //YOUR SQL COMMAND TO CREATE A TABLE
SqlCommand create = new SqlCommand(createString, myConn);
myConn.Open();
create.ExecuteNonQuery();
myConn.Close();
return true;
}
//Add the element's values to the database/table to later recall/reorder
public bool addElement(LogParse log,int num)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into storage(ID, Level, LevelInt, DateTime, Counter, Device, Source, Description) values(" + num + ",#Level, #LevelInt, #DataTimeItem,#counterItem,#deviceItem,#sourceItem,#descItem)", con);
cmd.Parameters.AddWithValue("#Level", log.Level);
cmd.Parameters.AddWithValue("#LevelInt", log.LevelInt);
cmd.Parameters.AddWithValue("#DataTimeItem", log.TimeStamp);
cmd.Parameters.AddWithValue("#counterItem", log.SequentialNumber);
cmd.Parameters.AddWithValue("#deviceItem", log.Device);
cmd.Parameters.AddWithValue("#sourceItem", log.Source);
cmd.Parameters.AddWithValue("#descItem", log.Description);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
return false;
}
return true;
}
//outputs a string array with all the values in the database
public LogParse[] readValue(int start, int end)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
con.Open();
LogParse[] s = new LogParse[end - start];
try
{
using (var oCommand = new SqlCommand("SELECT * From storage WHERE ID BETWEEN #Start AND #End", con))
{
oCommand.Parameters.AddWithValue("#Start", start);
oCommand.Parameters.AddWithValue("#End", end);
using (var oReader = oCommand.ExecuteReader())
{
int i = 0;
while (oReader.Read() && i < end-start)
{
//s[i] = oReader.GetString(1) + oReader.GetString(2) + oReader.GetString(3);
String Level = oReader.GetString(1);
Int32 LevelInt = oReader.GetInt32(2);
String Datetime = oReader.GetString(3);
Int16 SequentialNumber = (Int16)oReader.GetValue(4);
String Device = oReader.GetString(5);
String Source = oReader.GetString(6);
String Description = oReader.GetString(7);
s[i] = new LogParse();
s[i].Level = Level;
s[i].LevelInt = LevelInt;
s[i].TimeStamp = DateTime.Parse(Datetime);
s[i].SequentialNumber = SequentialNumber;
s[i].Device = Device;
s[i].Description = Description;
s[i].Source = Source;
++i;
}
}
}
}
catch
{
}
con.Close();
return s;
}
//Deletes the database by a query statement
//a return value of true means the delete was succesful
public static bool deleteDatabase()
{
String str;
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=Master;Integrated Security=True");
str = #"ALTER DATABASE MyDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE;DROP DATABASE [MyDatabase]";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
return true;
}
}
DON'T create another database, or table, it's evil. Just add Instance ID into table storage. And when writing new logs just add instance ID, same goes when reading from DB, put instance ID into where clause.
Another issue is to pick good Instance ID, your scenario is not very clear to me, but if you want every new application instance to have separate data, just create new GUID and use it as Instance ID.
For example you can have static property InstanceID in your Database class, and your class could look something like this :
public class Database
{
public static Guid InstanceID = new Guid();
//Add the element's values to the database/table to later recall/reorder
public bool addElement(LogParse log,int num)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into storage(ID, InstanceID, Level, LevelInt, DateTime, Counter, Device, Source, Description) values(" + num + ",#Level, #LevelInt, #DataTimeItem,#counterItem,#deviceItem,#sourceItem,#descItem)", con);
// writing InstanceID
cmd.Parameters.AddWithValue("#InstanceID", Database.InstanceID);
cmd.Parameters.AddWithValue("#Level", log.Level);
cmd.Parameters.AddWithValue("#LevelInt", log.LevelInt);
cmd.Parameters.AddWithValue("#DataTimeItem", log.TimeStamp);
cmd.Parameters.AddWithValue("#counterItem", log.SequentialNumber);
cmd.Parameters.AddWithValue("#deviceItem", log.Device);
cmd.Parameters.AddWithValue("#sourceItem", log.Source);
cmd.Parameters.AddWithValue("#descItem", log.Description);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
return false;
}
return true;
}
//outputs a string array with all the values in the database
public LogParse[] readValue(int start, int end)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
con.Open();
LogParse[] s = new LogParse[end - start];
try
{
// select with InstanceID
using (var oCommand = new SqlCommand("SELECT * From storage WHERE InstanceID = #InsID ID BETWEEN #Start AND #End", con))
{
oCommand.Parameters.AddWithValue("#Start", start);
oCommand.Parameters.AddWithValue("#End", end);
oCommand.Parameters.AddWithValue("#InsID", Database.InstanceID);
using (var oReader = oCommand.ExecuteReader())
{
int i = 0;
while (oReader.Read() && i < end-start)
{
//s[i] = oReader.GetString(1) + oReader.GetString(2) + oReader.GetString(3);
String Level = oReader.GetString(1);
Int32 LevelInt = oReader.GetInt32(2);
String Datetime = oReader.GetString(3);
Int16 SequentialNumber = (Int16)oReader.GetValue(4);
String Device = oReader.GetString(5);
String Source = oReader.GetString(6);
String Description = oReader.GetString(7);
s[i] = new LogParse();
s[i].Level = Level;
s[i].LevelInt = LevelInt;
s[i].TimeStamp = DateTime.Parse(Datetime);
s[i].SequentialNumber = SequentialNumber;
s[i].Device = Device;
s[i].Description = Description;
s[i].Source = Source;
++i;
}
}
}
}
catch
{
}
con.Close();
return s;
}
}
btw. DON'T swallow exceptions ! I leave your code the same but please don't do that, it's also evil, another thing is if there is a exception in your addElement method your connection will not be closed, use Using statement.
that doesn't sound safe at all, maybe one database with several user tables to store the logfiles for each user, but this just doesn't sound right to me.
otherwise a variable that is assigned randomly when the application is started in place of the database name when it is created.
but if you do something wrong there are going to be a lot of databases out there, but it looks like you have figured out sizing and some other things to keep them from overpowering the server machine.
Additional Information from Comment
if you are going to use tables on the Database(which I think is what you really need) then create the database separate and then create randomly named tables inside your application every time it is opened, you may want to have another table that would keep track of the the tables and the times they were opened as well, perhaps even what user opened them and such things like that

Error While Creating Database in SQL

I am new to SQL and trying to create a Database using C#. Here is my Code...
private void CreateDBBtn_Click(object sender, EventArgs e)
{
String connectionString = GetConnectionString();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
String SQLCommand = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'D:\\MyDatabase.mdf'," +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)";
SqlCommand cmd = new SqlCommand(SQLCommand, connection);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ae)
{
MessageBox.Show(ae.Message);
}
}
private String GetConnectionString()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = #".\SQLSERVER";
builder.AttachDBFilename = #"D:\MyDatabase.mdf";
builder.IntegratedSecurity = true;
builder.ConnectTimeout = 30;
builder.UserInstance = true;
return builder.ConnectionString;
}
but it gives me error that...
Where as D:\MyDataBase.mdf file has size 3.13 MB on my PC.
I completely agree with DJ KRAZE. It would take about two seconds to create that using whatever server manager you have.

Deleting row in a table not workng

I am trying to delete a row in my users_stocks table.
I use this code:
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM " + "users_stocks" + " WHERE user_name = '" + user_name + "'" + " AND " + "stock_symbol = " + "'" + stock_symbol + "'" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
There is a row with this data, but the query wont erase it.
What am i missing?
Use parametrized query to avoid Sql Injection Attacks and quoting problems
Not to mention that a parametrized query could be stored by the optimization engine of SqlServer and reused more quickly. An hand made query will be reevaluated every time you send to the database-
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM users_stocks " +
"WHERE user_name = #name AND stock_symbol = #stock" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
cmdnon.Parameters.AddWithValue("#name", user_name);
cmdnon.Parameters.AddWithValue("#stock", stock_symbol);
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
As Luis Quijada mentioned above use parameters, they are much safer. In the code below just change the YOUR_CONNECTION_STRING value and the SqlDbType to the ones matching in your DB.
public bool removeStock(string user_name, string stock_symbol)
{
using(SqlConnection connection = new SqlConnection("YOUR_CONNECTION_STRING"))
{
using(SqlCommand command = new SqlCommand())
{
try
{
command.Connection = connection;
command.CommandText = "DELETE FROM user_stocks WHERE user_name=#USERNAME AND stock_symbol=#STOCKSYMBOL";
command.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_name.Trim();
command.Parameters.Add("#STOCKSYMBOL", SqlDbType.VarChar).Value = stock_symbol.Trim();
connection.Open();
int i = command.ExecuteNonQuery();
if (i == 0)
return false;
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
finally
{
connection.Close();
}
}
}
}
Try this code :
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM users_stocks
WHERE user_name = '" + user_name + "'
AND stock_symbol = '" + stock_symbol + "'" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
Change in query

Update Query problem in asp.net c# and Mysql using odbc

when i specify values in my update query the query works fine and the database gets updated, but when i use parameters in my query the database does not update
here is the code i have written
try
{
OdbcConnection MyConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
MyConnection.Open();
String MyString = "UPDATE orddetpabak SET jud1=#jud1,jud2=#jud2,jud3=#jud3,adv=#adv where fil_no=#fil_no AND orderdate=#orderdate";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
String j1=DropDownList4.SelectedValue;
String j2=DropDownList5.SelectedValue;
String j3=DropDownList6.SelectedValue;
String j4=TextBox4.Text;
String j5 = HiddenField1.Value;
String j6 = TextBox3.Text;
MyCmd.Parameters.AddWithValue("#jud1",j1);
MyCmd.Parameters.AddWithValue("#jud2",j2);
MyCmd.Parameters.AddWithValue("#jud3",j3);
MyCmd.Parameters.AddWithValue("#adv",j4);
MyCmd.Parameters.AddWithValue("#fil_no",j5);
MyCmd.Parameters.AddWithValue("#orderdate",j6);
Response.Write(DropDownList4.SelectedValue);
Response.Write(" " + DropDownList5.SelectedValue);
Response.Write(" " + DropDownList6.SelectedValue);
Response.Write(" " + TextBox4.Text);
Response.Write(" " + HiddenField1.Value);
Response.Write(" " + TextBox3.Text);
MyCmd.ExecuteNonQuery();
//MyConnection.Close();
}
catch(Exception epp)
{
Response.Write(epp);
}
Please Help
As far as I know you cannot use named parameters in MySQL. If you change your string to be
String MyString = "UPDATE orddetpabak SET jud1=?,jud2=?,jud3=?,adv=?
where fil_no=? AND orderdate=?";
and your parameters as:
MyCmd.Parameters.AddWithValue("",j1);
MyCmd.Parameters.AddWithValue("",j2);
MyCmd.Parameters.AddWithValue("",j3);
MyCmd.Parameters.AddWithValue("",j4);
MyCmd.Parameters.AddWithValue("",j5);
MyCmd.Parameters.AddWithValue("",j6);
Hope this helps.
It can be like the following: (I'm using the ADO.NET driver for MySQL version 6.3.7.0, latest one had some issues).
public bool UpdateCustomerIAR(IAR oIAR)
{
bool bRetVal = false;
try
{
MySqlConnection dbConnection = new MySqlConnection(APPSConn.ConnectionString);
MySqlCommand dbCommand = dbConnection.CreateCommand();
string szSQL = string.Empty;
szSQL = "UPDATE schema.table_name SET field_name_one=?field_name_one";
szSQL += " WHERE field_name_two=?field_name_two";
using (MySql.Data.MySqlClient.MySqlConnection conn = new
MySql.Data.MySqlClient.MySqlConnection(APPSConn.ConnectionString))
{
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = szSQL;
cmd.Parameters.AddWithValue("?field_name_one", oIAR.Title);
cmd.Parameters.AddWithValue("?field_name_two", oIAR.IARID.ToString());
conn.Open();
cmd.ExecuteNonQuery();
bRetVal = true;
}
return bRetVal;
}
catch (MySqlException ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
catch (Exception ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
}

Categories