I am developing a windows project in dot net using c sharp language and the back-end is sql server database.
What I am doing is that there is a SQL query to insert data in the table as
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source = ...........";
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO TableName(column1, column2) VALUES(txtBox1, txtBox2)", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
Dataset ds = new Dataset();
Now, what problem I am facing here is that when I try to access this table in another windows form using Microsoft Report Viewer. Then, there the data newly inserted is not accessible since it needs the database to be refreshed.
Please tell me how can I resolve this problem.
Thanks in advance
Deepak
i don't think that you need to refresh it, just request it from db and commit transaction if you are using it. But if you want to share data between your forms use Registry pattern to achieve this.
Registry is class which will hold data for you, and you can access it from anywhere but use static variables and methods.
public class Registry
{
public static DataTable Users;
}
And if you change data from one form all forms will have updated data.
It seems there are many error,change this line
SqlCommand cmd = new SqlCommand("INSERT INTO TableName(column1, column2) VALUES(txtBox1, txtBox2)", con);
to
SqlCommand cmd = new SqlCommand(String.format("INSERT INTO TableName(column1, column2) VALUES('{0}', '{1}')",txtBox1.Text,txtBox2.Text), con);
and your command never executed on database
Related
I just finished to save a text from a richtextbox into sql database. Here you have the code:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[FISIER] (File_name,The_text) VALUES (#File_name,#The_text)", con);
cmd.Parameters.Add("#File_name", textBox1.Text);
cmd.Parameters.AddWithValue("#The_text", richTextBox1.Rtf);
cmd.ExecuteNonQuery();
con.Close();
}
Here is the table Click here for table
Now, my problem is that I don't know how to retrive the text from the database. As you see there the text I had saved into The_text and the data type is Text. I want to retrive the data back into richtextbox.
A quick search would have revealed the answer to this. For example, here is some sample code that queries a database table...
// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();
You can change the table name and fields to match your database.
This code was found at http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson03, but there are millions of other sites that will teach you this stuff.
I have added a SQL Server .mdf database file to my C# application, but when I try to connect with this code, the program causes a connection error.
CODE:
DataSet data;
string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";
try
{
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
connection.Close();
}
}
catch
{
MessageBox.Show("\n Problemi di connessione al database");
}
The error is:
ERROR IMAGE
Here are a couple observations:
Your connection string will need to be modified. Try using
string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
using Windows Authentication or this:
string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"; using standard security, Source: connectionstrings.com. This should be managed some other way than in code as well. Desktop applications can be de-compiled, and if the password changes, you would need a rebuild. In a ASP.NET application, Microsoft advises to use a web.config file or in the windows registry using a custom subkey.
You will want to use ExecuteReader() for a SELECT statement as ExecuteNonQuery() will not return a result set. See this answer that describes the differences in the types of SQL Server methods
you don't need connection.Close();, the using statement will handle that.
I currently have a dataset and would like to continually add new items to that dataset (like type a new entry in a textbox and add it with a button) and edit current items via the applications form I created.
How would I go about tackling this issue?
edit:
This was the best base start I could come up with watching videos and going through google. Dictionary.mdf is my dataset
SqlCommand cmd = new SqlCommand("insert into dictionary(word, definition) values(#word, #definition)");
cmd.Parameters.AddWithValue("#word", textBoxWordtoAdd.Text);
cmd.Parameters.AddWithValue("#definition", textBoxDefinition.Text);
this.Close();
I think you are missing the cmd.ExecuteNonQuery();
If you were using Ms Sql Server. Then your code should look something like this:
using(SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string sql = "insert into dictionary(word, definition) values(#word, #definition)";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.Add("#word", SqlDbType.Varchar, 50).value = textBoxWordtoAdd.Text;
cmd.Parameters.Add("#definition", SqlDbType.Varchar, 50).value = textBoxDefinition.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
You also need to open a conneciton which I don't see in your code, but I assume you do it somewhere. Just replace the ConnectionString in the code with your own connection string.
The programs I am using are WAMP server (and its mysql feature in particular) and MS Visual Studio 2010 and I am programming in C#
Basically, here is what I need and can currently do with my application.
I have several datagridview's throughout the project and the first is simple, it loads all data from a specific table in the database at the push of a button. I have another form which I can insert records and have somehow managed to make a delete function which asks the user for 2 fields (first name and last name) and then it places these into a query and carries out the command.
What do I need to do?
I need to be able to implement some way for the form to update the database. I have chosen to do this through a datagridview control so the user can see what they are editting whilst they edit it.
I have the following code which I have tried to update the database based on the data in the datagridview control.
string connString = "server=localhost;User Id=root;database=collegelist;";
MySqlConnection conn = new MySqlConnection(connString);
string selectSQL = "SELECT * FROM collegeemployee";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
DataTable table = new DataTable();
try
{
dgView2.Rows.RemoveAt(dgView2.CurrentRow.Index);
da.Update(table);
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
the problem with this code (listed in a method obviously) is that while the grid is able to be modified, it is unable to pass the data back to the database.
Instead of updating your database with the empty table what you should do is.
i.Get the datasource . like
ii. Update/synchronize the data source and data adapter
Here is the code it should work, if it doesn't please comment and tell me the problem.
string connString = "server=localhost;User Id=root;database=collegelist;";
MySqlConnection conn = new MySqlConnection(connString);
string selectSQL = "SELECT * FROM collegeemployee";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(selectSQL, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
BindingSource BindingSourceToUpdate = (BindingSource)dgView2.DataSource; // because direct casting to data table was failing in VS2o1o
try
{
dgView2.Rows.RemoveAt(dgView2.CurrentRow.Index);
da.Update((DataTable)BindingSourceToUpdate.DataSource);
}
catch(exception)
{
}
conn.close();
Further to my recent questions, I've now closed most of the connections that our web application was leaving open. However, the connection created by the function below remains open. Can anyone identify why it is not closing?
public DataTable GetSubDepartment(int deptId)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(Defaults.ConnStr))
{
SqlCommand cmd = new SqlCommand("proc_getDepartmentChild", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#dptParent", deptId));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
}
return dt;
}
* EDIT *
Following #HenkHolterman's comment:
I'm using SQL Server Management Studio Activity log to view the open connections. This one is listed as sleeping. SO what you say makes sense. Is there any way I can tell that this is a pooled connection rather than an open one?
Most probably because it went back to the connection pool.
Call
SqlConnection.ClearAllPools();
to clear the pool, then it should disappear. This could sometimes be useful, but is usually not needed.
I would assume that it's hanging in the connectionpool