I have created a WPF desktop application before and I was able to write up the code to save data from a textbox to a table I created in sql server 2012. I tried to create a WPF Web browser application and the same code was not working to save my data to my sql database. I am now trying to create another WPF desktop application and the same code that worked the last time is not working anymore. Please look at my code and help.
private void savebuyers_Click(object sender, RoutedEventArgs e)
{
string connectionstring = null;
connectionstring = "Data Source=FRANCIS;Initial Catalog=Pam Golding;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionstring);
try
{
string query;
query = "insert into buyers (name,number,email) values ('" + namebuyers.Text + "'," + Convert.ToInt32(numberbuyers) + ",'" + emailbuyers.Text + "')";
SqlCommand command = new SqlCommand(query, con);
message1.Text = "Data Saved Successfully!";
con.Open();
command.ExecuteNonQuery();
con.Close();
}
catch
{
message1.Text = "Error While Saving Data!";
}
}
You have missed the Text property of numberbuyers. So it is unable to cast object of type TextBox to type System.IConvertible.
You can fix it like this:
Convert.ToInt32(numberbuyers.Text)
Also you should always use parameterized queries to avoid Sql Injection.
Related
I tried to connect the database to the user control that has in my desktop application. the catch block is running. can anyone see any error in here?
can someone help to find the correct code to connect SQL server management studio 2014 to windows form Application?
I have tried the code as we use to windows form. but it isn't working .is there any different code that uses to user control database connection?
SqlCommand cmd;
SqlConnection con;
private void btnsave_Click(object sender, EventArgs e) {
try {
con = new SqlConnection(# "Data Source=LAPTOP-EN6B5ABV;Initial Catalog=nature;Integrated Security=True");
con.Open();
cmd = new SqlCommand("INSERT INTO crop" + " (cropid, cropname, scnname, noofplant, culdate, ferttimeperiod, harvetimeperiod, addeddate,lifetime,lifetimeperiod) VALUES (#cropid, #cropname, #scnname, #noofplant, #culdate, #ferttimeperiod, #harvetimeperiod, #addeddate,#lifetime,#lifetimeperiod)", con);
cmd.Parameters.AddWithValue("#cropid", txtcropid.Text);
cmd.Parameters.AddWithValue("#cropname", txtcropname.Text);
cmd.Parameters.AddWithValue("#scnname", txtscnname.Text);
cmd.Parameters.AddWithValue("#noofplant", textBox1.Text);
cmd.Parameters.AddWithValue("#culdate", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#ferttimeperiod", comfert.SelectedItem);
cmd.Parameters.AddWithValue("#harvetimeperiod", comboBox1.SelectedItem);
cmd.Parameters.AddWithValue("#lifetime", textBox2.Text);
cmd.Parameters.AddWithValue("#lifetimeperiod", combolifetime.SelectedItem);
cmd.Parameters.AddWithValue("#addeddate", addeddate.Text);
cmd.ExecuteNonQuery();
con.Close();
} catch (Exception) {
MessageBox.Show("something went wrong in database server");
}
I expect the insertion of the data.
Here is my code that I got the correct output. There was an error related to the datetimepicker value. When Get the selected value of datetimepicker it was given an error.
I used this statement to insert date to the database.
cmd.Parameters.AddWithValue("#culdate", Convert.ToDateTime(dateTimePicker1.Value));
string date =DateTime.Now.ToShortDateString();
cmd.Parameters.AddWithValue("#cropid", txtcropid.Text);
cmd.Parameters.AddWithValue("#cropname", txtcropname.Text);
cmd.Parameters.AddWithValue("#scnname", txtscnname.Text);
cmd.Parameters.AddWithValue("#noofplant", txtnoofplant.Text);
cmd.Parameters.AddWithValue("#culdate", Convert.ToDateTime(dateTimePicker1.Value));
cmd.Parameters.AddWithValue("#ferttimeperiod", txtharvtime.Text);
cmd.Parameters.AddWithValue("#fert", comfert.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#harvtimeperiod", txtharvtime.Text);
cmd.Parameters.AddWithValue("#harv", comboBox1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#addeddate", date);
cmd.Parameters.AddWithValue("#lifetimeperiod", txtlifetime.Text);
cmd.Parameters.AddWithValue("#life", combolifetime.SelectedItem.ToString());
cmd.ExecuteNonQuery();
con.Close();
string msg = "Crop Details are successfully saved...";
string title = "Saved";
System.Media.SystemSounds.Asterisk.Play();
MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.None);
This error occurs whenever i'm trying to run my program.
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
The code is as follows:
private void create_Click(object sender, EventArgs e)
{
string MyConnectionString = "Server=x.x.x.x;Database=groupdes_New;Uid=root;Pwd=password;";
//create connection
MySqlConnection connection = new MySqlConnection(MyConnectionString);
//connect to database
connection.Open();
MySqlCommand cmd;
cmd = connection.CreateCommand();//create command
cmd.CommandText = "CREATE Table Newtable (" + "name" + ")";
cmd.ExecuteNonQuery();
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
I still can't manage to solve this error. Thanks for the help!
Your create table sintaxis is wrong.
You need define field datatype
CREATE TABLE Table1
(`myDate` datetime)
;
I know that it is an easy problem but I can't find the error. I want to save data in my database. I create a database named "Examen" with Microsoft SQL Server 2008 then in my app in visual studio I make the connection string like this :
string connectionstring = #"Data Source=.\sqlexpress;Initial Catalog=Examen;Integrated Security=True";
Then I use this code to insert data into a "Test" table:
MySqlConnection connection = new MySqlConnection(connectionstring);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "Insert into Examen.Test (nom,prenom) values (" + txbnom.Text + "," + txbprenom.Text + ") ";
cmd.ExecuteNonQuery();
MessageBox.Show("ok");
}
catch (Exception)
{
throw;
}
finally
{
if(connection.State == ConnectionState.Open)
{
connection.Close();
}
}
When running this code i had an error when openning the connection
Unable to connect to any of the specified MySQL hosts.
You are mixing MySQL and MSSQL.
Are you sure you want to connect to a MySQL server? Use http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx if you would like to connect to MSSQL.
Also you should make yourself familiar with SQL injection
I am using this code to delete a database through C#
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 = "DROP DATABASE [" + DbName + "]";
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
else
{
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
con.Close();
con.Dispose();
result = 1;
}
catch (Exception ex)
{
result = 0;
}
return result;
But I get an error
Database currently in use
Can anyone help?
Try this:
String sqlCommandText = #"
ALTER DATABASE " + DbName + #" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [" + DbName + "]";
Also make sure that your connection string defaults you to the master database, or any other database other than the one you're dropping!
As an aside, you really don't need all of that stuff around your queries. The ConnectionState will always start off Closed, so you don't need to check for that. Likewise, wrapping your connection in a using block eliminates the need to explicitly close or dispose the connection. All you really need to do is:
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
using(SqlConnection con = new SqlConnection(Connectionstring)) {
con.Open();
String sqlCommandText = #"
ALTER DATABASE " + DbName + #" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [" + DbName + "]";
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
result = 1;
Here is how you do it using Entity Framework version 6
System.Data.Entity.Database.Delete(connectionString);
You should take a look at SMO.
These allow you to manage all aspects of SQL Server from code, including deleting of databases.
The database object has a Drop method to delete database.
Create sqlconnection object for different database other than you want to delete.
sqlCommandText = "DROP DATABASE [DBNAME]";
sqlCommand = new SqlCommand(sqlCommandText , sqlconnection);
sqlCommand.ExecuteNonQuery();
In this case i would recommend that you take the database offline first... that will close all connections and etc... heres an article on how to do it: http://blog.sqlauthority.com/2010/04/24/sql-server-t-sql-script-to-take-database-offline-take-database-online/
Microsoft clearly states that A database can be dropped regardless of its state: offline, read-only, suspect, and so on. on this MSDN article (DROP DATABASE (Transact-SQL))
Connection pooling at a guess, use sql server's activity monitor to make sure though.
Pooling keeps connections to the database alive in a cache, then when you create a new one, if there's one in the cache it hands it back instead of instantiating a new one. They hang around for a default time, (2 minutes I think) if they don't get re-used in that time, then they killed off.
So as a first go connect straight to master, instead of using change database, as I suspect change database will simply swap connections in the pool.
Add a check routine for database in use (use a connection to master to do it!). You can force the database to be dropped anyway by first executing
ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
again from the connection to master!
However everybody else using the db, will no longer like you at all...
Just don't use DB name in connection string.
"Data Source=.\SQLEXPRESS;Integrated Security=True;"
I was having the same troubles as Anshuman...
By my testing of the code in question of Anshuman there have been very simple error:
there have to be SqlConnection.ClearAllPools(); instead of SqlConnection.ClearPool(con);
Like this trouble of
"cannot drop database because is in use..."
disappears.
I have to populate checkboxes with data coming from database, but no checkboxes are showing on my page. Please let me know the correct way to do that. In C#, the page_load method I've written is this:
public partial class dbTest1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string Server = "al2222";
string Username = "hshshshsh";
string Password = "sjjssjs";
string Database = "database1";
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;
string query = "Select * from Customer_Order where orderNumber = 17";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (!IsPostBack)
{
Interests.DataSource = dr;
Interests.DataTextField = "OptionName";
Interests.DataValueField = "OptionName";
Interests.DataBind();
}
}
conn.Close();
conn.Dispose();
}
}
}
}
And in the .aspx, I have this:
<asp:CheckBoxList ID="Interests" runat="server"></asp:CheckBoxList>
Please tell me the correct way to accomplish this.
Although your question is already answered (via the connection string comments), I thought I'd chime in with a possible way to rewrite this. I'd started this off as a comment, but it got a bit long and unwieldy. Note that this doesn't directly answer your question, but it is something to consider for code cleanliness and a possible (likely very mild) performance boost on postbacks.
protected void Page_Load(object sender, EventArgs e)
{
// If we're in postback, let's not poll the database.
if (Page.IsPostback)
return; // Change this if you do need some postback processing here.
// I assume that in the real world you pull this info from web.config
string Server = "al2222";
string Username = "hshshshsh";
string Password = "sjjssjs";
string Database = "database1";
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;
string query = "Select * from Customer_Order where orderNumber = 17";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
// Going to assume that you're only getting 1 record
// due to apparent key (orderNumber = 17) in query?
// You can also consider "if (dr.Read())", but fundamentally
// they will do the same thing.
while (dr.Read())
{
Interests.DataSource = dr;
Interests.DataTextField = "OptionName";
Interests.DataValueField = "OptionName";
Interests.DataBind();
}
// I've excised the calls to .Close() and .Dispose(),
// as the using block covers them for you.
}
}
}
Why would we go this route?
In your original code, you were polling the database (and potentially looping, if my assumption about that being a single-record query was wrong) every page load, whether or not you were in postback. You weren't checking postback until you were inside the loop, where the damage was mostly already done. In the code I've listed, you short-circuit out of Page_Load() altogether if you're in postback. You can, of course, change that to an if/else and bracket the groups if you need some load-event processing on postbacks as well. This also simplified your in-loop code.
Your using blocks covered the disposal/closure of the connection for you. Thus, you do not need that additional code.
As OrbMan stated in the comments, hopefully in your actual code you're retrieving all the connection string info from your web.config file instead of hard-coding it, correct?
Final final unrelated note: This is a lot of data access code that newer versions of the .NET Framework simplify greatly with tools such as Entity Framework and LINQ-to-SQL. There are also 3rd-party data access layer tools (such as SubSonic and ActiveRecord) that will simplify this. Using tools such as those will greatly reduce the amount of code you're writing here -- and I'm guessing you're using quite a bit of similar code throughout your app as well, so those tools will provide you the developer with quite the productivity boost. (And much simpler down-the-road maintenance.)
Just food for thought.