Error Creating DataBase name - c#

I am trying to create a database here, I am able to create it with just a single word like "test" or "example". However, when i tried to create a database name, 2 words with a spacing in the middle for example "testing table" , it does not create the database. I tried [],'' and {} but it did not worked. Here is my code.
str = "CREATE DATABASE "+textBox1.Text+" ON PRIMARY " +
"(NAME = "+textBox1.Text+"_Data, " +
"FILENAME = 'C:\\"+textBox1.Text+".mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = "+textBox1.Text"+_Log, " +
"FILENAME = 'C:\\"+textBox1.Text"+.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";

From this article Create a SQL Server database using C#, you could try sanitizing your input, for example:
private void button2_Click(object sender, System.EventArgs e)
{
DatabaseParam DBParam = new DatabaseParam();
DBParam.DatabaseName = textBox1.Text;
//Assign Data file parameters
DBParam.DataFileGrowth = "10%";
DBParam.DataFileName = textBox3.Text;
DBParam.DataFileSize = "2";//2MB at the init state
DBParam.DataPathName = textBox2.Text;
//Assign Log file parameters
DBParam.LogFileGrowth = "10%";
DBParam.LogFileName = textBox10.Text;
DBParam.LogFileSize = "1";//1MB at the init state
DBParam.LogPathName = textBox11.Text;
CreateDatabase(DBParam);
}
private void CreateDatabase(DatabaseParam DBParam)
{
System.Data.SqlClient.SqlConnection tmpConn;
string sqlCreateDBQuery;
tmpConn = new SqlConnection();
tmpConn.ConnectionString = "SERVER = " + DBParam.ServerName + "; DATABASE = master; User ID = sa; Pwd = sa";
sqlCreateDBQuery = " CREATE DATABASE " + DBParam.DatabaseName + " ON PRIMARY "
+ " (NAME = " + DBParam.DataFileName +", "
+ " FILENAME = '" + DBParam.DataPathName +"', "
+ " SIZE = 2MB,"
+ " FILEGROWTH =" + DBParam.DataFileGrowth +") "
+ " LOG ON (NAME =" + DBParam.LogFileName +", "
+ " FILENAME = '" + DBParam.LogPathName + "', "
+ " SIZE = 1MB, "
+ " FILEGROWTH =" + DBParam.LogFileGrowth +") ";
SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
try
{
tmpConn.Open();
MessageBox.Show(sqlCreateDBQuery);
myCommand.ExecuteNonQuery();
MessageBox.Show("Database has been created successfully!", "Create Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Create Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
tmpConn.Close();
}
return;
}
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
textBox3.Text = textBox1.Text + "_Data";
textBox10.Text = textBox1.Text + "_Log";
}

Related

how to convert value stored in session as an integer

I am trying to save data into my database using the value stored in a session, however, the value must be of type int as stated in the database. how do I go about doing this? the code for the insertion is below.
protected void btnSave_outcome_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand sqlCmd = new SqlCommand("OutcomeCreateOrUpdate", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#outcomeID", (hfoutcomeID.Value == "" ? 0 : Convert.ToInt32(hfoutcomeID.Value)));
sqlCmd.Parameters.AddWithValue("#learning_activity", (ddlActivity.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
sqlCmd.Parameters.AddWithValue("#audience", (txtAudience1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#condition", (txtCondition1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#bloom_level", (ddlCategory1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#verb", (ddlVerb1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#product", (txtProduct2.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#degree", (txtDegree1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#statement", ("Given " + txtCondition1.Text.Trim() + ", " + txtAudience1.Text.Trim() + " Will be able to " + ddlVerb1.SelectedItem.Text + " " + txtProduct2.Text.Trim()+ " " + txtDegree1.Text.Trim() +"."));
//sqlCmd.Parameters.AddWithValue("#moduleID", (ddlmodules.SelectedIndex));
sqlCmd.ExecuteNonQuery();
con.Close();
//string objectiveID = hfobjectiveID.Value;
string outcomeID = hfoutcomeID.Value;
Clear();
if (outcomeID == "")
lblSuccessMessage.Text = "Saved Successfully";
else
lblSuccessMessage.Text = "Updated Successfully";
//FillGridView(); for outcomes
new_outcome.Visible = true;
}
and I created the session as follows
protected void redirect_outcomes_Click(object sender, EventArgs e)
{
Session["objectiveID"] = objectiveID.ToString();
//Session["module"] = ddlmodules.SelectedValue;
//Response.Redirect("learningoutcomes.aspx?MultiView1.ActiveIndex=" +2);
final_objective1.Text = "Given " + txtCondition.Text.Trim() + ", " + txtAudience.Text.Trim() + " Will be able to " + txtVerb.Text.Trim() + " " + txtProduct.Text.Trim() + " .";
MultiView1.Visible = false;
GoToAudience1.Visible = false;
MultiView2.ActiveViewIndex = 0;
}
Your code:-
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
My suggestion:-
if(Session["objectiveID"] != null)
{
sqlCmd.Parameters.AddWithValue("#objectiveID", Convert.ToInt32(Session["objectiveID"]));
}
No need to use try parse/parse because you are storing only integer value in session. So session have either empty or integer value.

SQLtransaction on multiple insert query

i get an error of
"This SqlTransaction has completed; it is no longer"
while multiple insert in a single table
mclDb.trans = mclDb.mCon.BeginTransaction();
try
{
foreach (DataGridViewRow dgvRow in dgvDetail.Rows) // get rows in details
{
ht.Clear();
string dtlPoCode = dgvRow.Cells[2].Value.ToString();
if (poCode == dtlPoCode) // check if po code matches
{
ht.Add("dtlPoCode", dtlPoCode);
ht.Add("dtlPoLine", dgvRow.Cells[3].Value.ToString());
ht.Add("dtlwhouse", dgvRow.Cells[12].Value.ToString());
ht.Add("dtlSkuCode", dgvRow.Cells[4].Value.ToString());
ht.Add("dtlUom", dgvRow.Cells[6].Value.ToString());
ht.Add("dtlmrQty", dgvRow.Cells[7].Value.ToString());
ht.Add("dtlBCode", dgvRow.Cells[10].Value.ToString());
ht.Add("dtlBExp", dgvRow.Cells[11].Value.ToString());
ht.Add("dtlBin", dgvRow.Cells[9].Value.ToString());
ht.Add("custPoCode", custPoCode);
ht.Add("grnCode", grnCode);
ht.Add("refCode", refCode);
mclDb.IUD(ht);
}
}
MessageBox.Show("Transaction Complete");
mclDb.trans.Commit();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "Error Encountered", MessageBoxButtons.OK, MessageBoxIcon.Error); mclDb.trans.Rollback();
}
here is my IUD method
public void IUD(Hashtable ht)
{
try
{
Connect();
string cmd = "";
cmd = mStatements.getQuery(ht);
mAdptr = new SqlDataAdapter(cmd,mCon);
ds = new DataSet();
mAdptr.Fill(ds);
}
catch (Exception Ex)
{
throw new Exception(Ex.Message);
}
}
and my getquery method
public string getQuery(Hashtable ht)
{
StringBuilder qry = new StringBuilder();
qry.Append(" Insert into mTable values ");
qry.Append(" ('" + ht["custPoCode"] + "','" + ht["dtlPoCode"] + "', ");
qry.Append(" " + ht["dtlPoLine"] + ",'" + ht["dtlwhouse"] + "', ");
qry.Append(" '" + ht["dtlSkuCode"] + "','" + ht["dtlUom"] + "', ");
qry.Append(" " + ht["dtlmrQty"] + ",'" + ht["grnCode"] + "', ");
qry.Append(" '" + ht["refCode"] + "','" + ht["dtlBCode"] + "', ");
qry.Append(" '" + ht["dtlBExp"] + "','" + ht["dtlBin"] + "', ");
qry.Append(" '" + ht["dtlmrQty"] + "','' ) ");
return qry.ToString();
}
the number of rows to be inserted in the table will depend on how many rows are selected in dgvDetail (which is a datagridview)
any suggestions in how to use sqltransaction on my codes ?
tia

How to create mdf database file dynamicly using C# code by optional "Recovery model" option?

I have created C# code which creates a .mdf SQL Server database file and this code works just fine.
There only few options are missing.
Especially I need to choose
either database "Recovery model" is full mode or simple mode and
either "Auto shrink" value is true or false during during creation of a database!
Code:
private void buttonCreateData_Click(object sender, EventArgs e)
{
String CreateDatabase;
SqlConnection connection = new SqlConnection("Server=(localdb)\\Projects;Integrated security=SSPI;database=master");
CreateDatabase = "CREATE DATABASE " + textBoxDataName.Text + " " +
"ON PRIMARY " +
"(NAME = '" + textBoxDataName.Text + "', " +
"FILENAME = '" + Directory.GetCurrentDirectory() + "\\" + textBoxDataName.Text + ".mdf', " +
"SIZE = 6MB, MAXSIZE = 4GB, FILEGROWTH = 10%) " +
"LOG ON " +
"(NAME = '" + textBoxDataName.Text + "_LOG" + "', " +
"FILENAME = '" + Directory.GetCurrentDirectory() + "\\" + textBoxDataName.Text + ".ldf', " +
"SIZE = 1MB, MAXSIZE = 200MB, FILEGROWTH = 10%)" +
"";
SqlCommand command = new SqlCommand(CreateDatabase, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Database is created successfully", "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
Remember I don't need to create the database firstly and then modify those two options. I need to set those two options during creation of database.
So what should I add in that code, I mean what kind of statement is missing in order to choose those two options during real-time?

EMPLOYEE MDB ACCESS GET ERROR 'Message: No value given for one or more required parameters'

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string gs_ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=YorkProducts.accdb;"
+ "Persist Security Info=False;";
public Form1()
{
InitializeComponent();
}
private void ClearForm()
{
tb_EmpNr.Clear();
tb_LastName.Clear();
tb_FirstName.Clear();
tb_MiddleName.Clear();
tb_Address.Clear();
tb_Zip.Clear();
tb_City.Clear();
tb_State.Clear();
tb_Phone.Clear();
tb_PayLevel.Clear();
tb_PayGrade.Clear();
tb_DOH.Clear();
}//end clear form
private void GetCityState()
{
try
{
//create the connection
string Query = "SELECT City, State " +
" FROM tbl_Zip WHERE Zip=" + "\"" + tb_Zip.Text + "\"" + "";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();
Reader.Read();
tb_City.Text = Reader.GetString(0);
tb_State.Text = Reader.GetString(1);
Reader.Close();
Connection.Close();
}//end try
catch (Exception error)
{
MessageBox.Show("Message: " + error.Message,
"EMPLOYEE MDB ACCESS GET ZIP ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}//end catch
}//end get city state
private void GetRecFromDatabase(string s_EmpNr)
{
try
{
//create the connection
string Query = "SELECT EmpNumber, EmpLastName, EmpFirstName, EmpMiddleName, EmpAddress, EmpZip," +
" EmpPhone, EmpPayLevel, EmpPayGrade, EmpHireDate" +
" FROM tbl_Employee WHERE EmpNumber=" + "\"" + s_EmpNr + "\"" + "";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();
Reader.Read();
tb_EmpNr.Text = Reader.GetString(0);
tb_LastName.Text = Reader.GetString(1);
tb_FirstName.Text = Reader.GetString(2);
tb_MiddleName.Text = Reader.GetString(3);
tb_Address.Text = Reader.GetString(4);
tb_Zip.Text = Reader.GetString(5);
tb_Phone.Text = Reader.GetString(6);
tb_PayGrade.Text = String.Format("{0}", Reader.GetInt32(7));
tb_PayLevel.Text = String.Format("{0}", Reader.GetInt32(8));
tb_DOH.Text = String.Format("{0:d}", Reader.GetDateTime(9));
Reader.Close();
Connection.Close();
GetCityState();
}//end try
catch (Exception error)
{
MessageBox.Show("Message: " + error.Message,
"EMPLOYEE MDB ACCESS GET ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}//end catch
}//end GetRecFromDatabase
private void b_Clear_Screen_Click_Click(object sender, EventArgs e)
{
ClearForm();
tb_EmpNr.Focus();
}
private void b_Add_Customer_Click(object sender, EventArgs e)
{
try
{
//create the connection
string Query = "INSERT INTO tbl_Employee (EmpNumber, EmpLastName, EmpFirstName, EmpMiddleName, " +
"EmpAddress, EmpZip, EmpPhone, EmpHireDate, EmpPayLevel, EmpPayGrade)" +
"VALUES(" + "\"" + tb_EmpNr.Text + "\"" + ", " //strings get double quotes
+ "\"" + tb_LastName.Text + "\"" + ", "
+ "\"" + tb_FirstName.Text + "\"" + ", "
+ "\"" + tb_MiddleName.Text + "\"" + ", "
+ "\"" + tb_Address.Text + "\"" + ", "
+ "\"" + tb_Zip.Text + "\"" + ", "
+ "\"" + tb_Phone.Text + "\"" + ", "
+ "#" + tb_DOH.Text + "#" + ", "
+ tb_PayLevel.Text + ", "
+ tb_PayGrade.Text
+ ")";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();
Reader.Close();
Connection.Close();
}//end try
catch (Exception error)
{
MessageBox.Show("Message: " + error.Message,
"EMPLOYEE MDB ACCESS ADD ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}//end catch
}
private void b_Get_Customer_Click(object sender, EventArgs e)
{//get a specific rec
GetRecFromDatabase(tb_EmpNr.Text);
}
private void tb_Zip_TextChanged(object sender, EventArgs e)
{//get the city and state
GetCityState();
}
private void b_Get_Next_Customer_Click(object sender, EventArgs e)
{//get next rec
string s_NextRec = Convert.ToString(Convert.ToInt32(tb_EmpNr.Text) + 1);
GetRecFromDatabase(s_NextRec);
}
private void b_Update_Customer_Click(object sender, EventArgs e)
{//update the record
try
{
string Query = "UPDATE tbl_Employee SET " +
"EmpLastName =" + "\"" + tb_LastName.Text + "\"" + ", " +
"EmpFirstName =" + "\"" + tb_FirstName.Text + "\"" + ", " +
"EmpMiddleName =" + "\"" + tb_MiddleName.Text + "\"" + ", " +
"EmpAddress =" + "\"" + tb_Address.Text + "\"" + ", " +
"EmpZip =" + "\"" + tb_Zip.Text + "\"" + ", " +
"EmpPhone =" + "\"" + tb_Phone.Text + "\"" + ", " +
"EmpHireDate =" + "#" + tb_DOH.Text + "#" + " " + ", " +
"EmpPayLevel =" + Convert.ToInt32(tb_PayLevel.Text) + ", " +
"EmpPayGrade =" + Convert.ToInt32(tb_PayGrade.Text) +
" WHERE EmpNumber =" + "\"" + tb_EmpNr.Text + "\"" + " ";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();
Reader.Close();
Connection.Close();
GetRecFromDatabase(tb_EmpNr.Text);
}//end try
catch (Exception error)
{
MessageBox.Show("Message: " + error.Message,
"EMPLOYEE MDB ACCESS ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}//end catch
}//end update click
}//end class
}//end namespace
This program is supposed to grab data from an access database that I have manually created and place the data into the fields of a form. I have placed the access database into the debug folder of the project(in visual studio) however I am receiving the error message stated in the title. I think it is possible that I have the database file in the wrong location? I have added Microsoft Access 14.0 as a reference and installed the Microsoft Access Database engine for my version of access. Any help would be appreciated! Thanks!
Solution 1:
string Query = "SELECT City, State FROM tbl_Zip WHERE Zip='" + tb_Zip.Text+"'";
Solution 2:
//create the connection
string Query = "SELECT City, State FROM tbl_Zip WHERE Zip=#zip";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Command.Parameters.AddWithValue("#zip",tb_Zip.Text);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();

On load event problem

I have a problem when I want to update a row in a database. The page that updates also adds a client but the problem is that when page load detects update button was pressed it seems to keep loading up the variables and I am unable to update my database.
public partial class CustomerInput : System.Web.UI.Page
{
string update, Id, Name, Address, Suburb, Postcode, Age, Email;
protected void Page_Load(object sender, EventArgs e)
{
update = Request.QueryString["Update"];
if (update == "true")
{
SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer");
Button1.Text = "Update";
Id = Request.QueryString["Id"];
connection.Open();
SqlCommand command = new SqlCommand("Select * from Customer where Id = " + Id, connection);
SqlDataReader read = command.ExecuteReader();
read.Read();
TextBox1.Text = read[1].ToString();
TextBox2.Text = read[2].ToString();
TextBox3.Text = read[3].ToString();
TextBox4.Text = read[4].ToString();
TextBox5.Text = read[5].ToString();
TextBox6.Text = read[6].ToString();
connection.Close();
update = string.Empty;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer");
if (Button1.Text == "Update")
{
connection.Open();
SqlCommand command;
Name = TextBox1.Text;
Address = TextBox2.Text;
Suburb = TextBox3.Text;
Postcode = TextBox4.Text;
Age = TextBox5.Text;
Email = TextBox6.Text;
command = new SqlCommand("UPDATE Customer SET Name = " + "'" + Name + "', " + "Address = " + "'" + Address + "', " + "Suburb = " + "'" + Suburb + "', "
+ "Postcode = " + "'" + Postcode + "', " + "Age = " + "'" + Age + "', " + "Email = " + "'" + Email + "' " + "Where Id =" + Id, connection);
command.ExecuteNonQuery();
connection.Close();
}
if (Button1.Text == "New Client")
{
Name = TextBox1.Text;
Address = TextBox2.Text;
Suburb = TextBox3.Text;
Postcode = TextBox4.Text;
Age = TextBox5.Text;
Email = TextBox6.Text;
Response.Write("Blah");
SqlCommand command = new SqlCommand("INSERT INTO Customer VALUES (" + "'" + Name + "'" + ", " + "'" + Address + "'" + ", " + "'" + Suburb + "'" + ", "
+ "'" + Postcode + "'" + ", " + "'" + Age + "'" + ", " + "'" + Email + "'" + ")", connection);
command.ExecuteNonQuery();
}
Button1.Text = "New Client";
}
}
}
At the start of your page load event you need to add an if statement to check if this is the first time the page loads:
example:
if (!IsPostBack)
{
... add your code here
}
I guess you need to use Page.IsPostBack:
if (Page.IsPostBack)
{
// Do Something ..
{
else
{
// Do something else ..
}

Categories

Resources