How to add items to existing database thru application form - c#

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.

Related

Getting a database error when trying to view data

Alright,
I have a page that interacts with my SQL data connection. it tries to run a stored procedure, but every time I run it, it locks out of the database showing this error:
Here's the code the fires of the connection and stored procedure `
FileUpload1.SaveAs(Server.MapPath("images//" + FileUpload1.FileName));
string Image = MapPath("images//" + FileUpload1.FileName);
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BOOKS.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("AddaBook", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.AddWithValue("#Image", SqlDbType.NVarChar).Value = Image;
cmd.Parameters.AddWithValue("#Author", SqlDbType.NVarChar).Value = txtAuthor.Text;
cmd.Parameters.AddWithValue("#PublishDate", SqlDbType.DateTime).Value = txtPublishDate.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Connection.Close();
lblUploadResult.Text = "File uploaded successfully.";
lblUploadResult.ForeColor = System.Drawing.Color.ForestGreen;
}`
Any help is appreciated and always thank you!
Try moving your mdf file out of OneDrive. Sometime when OneDrive is doing an upload, or one of the many other processes it does, it will lock the files - especially from system user.
It is saying that your database is under usage so you can not access it.
Be sure that no other code is accessed in the database without closing the connection.
You may also update the code with the following as some not needed lines are removed.
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BOOKS.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("AddaBook", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.AddWithValue("#Image", SqlDbType.NVarChar).Value = Image;
cmd.Parameters.AddWithValue("#Author", SqlDbType.NVarChar).Value = txtAuthor.Text;
cmd.Parameters.AddWithValue("#PublishDate", SqlDbType.DateTime).Value = txtPublishDate.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblUploadResult.Text = "File uploaded successfully.";
lblUploadResult.ForeColor = System.Drawing.Color.ForestGreen;
You already have the file open but just don't know it. For example, if you are trying to open a text file called Test.txt (or conversely a .mdf database file which has already been opened), then you will get this error, which is also why you are likely getting the other errors down the line but all related to this first error.
With databases, things can get a bit tricky, because you can connect to a database and at times get an error and be kicked out of the system without closing the connection or process... at which point a currently running but unknown process may be keeping the connection alive. You can look at all open processes on your system or see if you mistakenly have the connection open and then close it before trying to open it through the application.

How do i continuously update a value if it changed on the database

I'm trying to implement the status of a current logged in user in an WPF application. I can read from the database and set that value once , but i need it to keep updating. So for example when a user is online, and he changes to busy. The value would be online, but once it changed on the database to busy , the value would update to busy too.
for example:
connection = new MySqlConnection(connectionString);
Query = "SELECT status FROM Accounts WHERE username=#username";
connection = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(Query, connection);
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#username", thedesiredusername);
connection.Open();
MySqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
string userstatus = dataReader.GetString("status");
}
This would set the userstatus value once. How can i get it to do something like this:
connection = new MySqlConnection(connectionString);
Query = "SELECT status FROM Accounts WHERE username=#username";
connection = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(Query, connection);
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#username", thedesiredusername);
connection.Open();
MySqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
//keep doing:
if (userstatus != dataReader.GetString("status"))
{
string userstatus = dataReader.GetString("status");
}
}
Thanks in advance!
If you can identify when the login state will change or can identify an event that's convenient to check (page load), event driven models are typically more efficient. If you don't have this luxury, then you're left polling the database every so often to see if the status has changed. Consider adding the filter to the database query rather than the client side code.
Typically, the database query is the most expensive part of the polling check. Trying to save a couple of processing cycles by checking if the new acquired matches the last check, isn't providing any sort of massive performance boost.
I am now using Devart.Data.MySql Package. this does exactly what i need.

Running a t-sql stored procedure with EXECUTE AS statement with .NET SqlCommand

I have a .NET web service application that executes parameterized MS SQL Server stored procedures using System.Data.SqlCommand. The application receives a name of the stored procedure and its parameters from user input.
Also the application deployed within Windows AD domain and it is able to obtain the name of a remote user with the help of SSPI authentication.
using (var con = new SqlConnection(connectionString)) {
using (var cmd = new SqlCommand(procedureName, con)) {
cmd.CommandType = CommandType.StoredProcedure;
foreach (var pair in pairs.AllKeys) {
cmd.Parameters.Add(new SqlParameter(pair, pairs[pair]));
}
con.Open();
using (var reader = cmd.ExecuteReader()) {
// processing results
}
}
}
Now I want to execute a stored procedure with an EXECUTE AS statement.
use [db]
go
execute as user = 'domain\user' --execute as RemoteUser
exec [db].[stored_procdure] #param1=value1
Can this be done? How can I add EXECUTE AS to the SqlCommand?
I would not like to resort to sql injection prone code and build the sql request from strings received from user.
Solved it some time ago with a colleague of mine.
To achieve the requested behavior the execute as statement should be run in a separate preceeding SqlCommand while in the same SqlConnection.
After the closing of the reader, still in the same SqlConnection, there's another separate SqlCommand needed - revert - to switch back the context.
I was having a similar issue where I was able to Execute as User but the Revert wasn't working. By following prot's answer I was able to fix it. So for anyone having a similar issue this is how the code looks
SqlCommand cmd = new SqlCommand("EXECUTE AS USER = 'domain\\user';");
OSSDBDataContext dc = new OSSDBDataContext();
cmd.Connection = dc.Connection as SqlConnection;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
//Execute stored procedure code goes here
SqlCommand cmd2 = new SqlCommand("REVERT;");
cmd2.Connection = dc.Connection as SqlConnection;
cmd2.ExecuteNonQuery();

How to restore back up programmatically

I created a backup on button click
My code for this is
con.Open();
string str = "USE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf]";
string str1 = "BACKUP DATABASE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf] TO DISK = 'C:\\Users\\Public\\aa.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";
SqlCommand cmd1 = new SqlCommand(str, con);
SqlCommand cmd2 = new SqlCommand(str1, con);
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
MessageBox.Show("success");
con.Close();
Now I would like to restore the backed up database, please help I searched lots of questions, but I didn't get the answer I need - please help me to perform this task.
I tried to restore using this code:
string query = "RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE";
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.ExecuteNonQuery();
}
con.Close();
but I am getting an error
Please help me with this
Each of the physical files needs to reside somewhere on the system that you're attempting to restore the backed up database to. The error message is telling you that the files are in use by another database. You can query sys.master_files to find out which database they belong to.
To resolve this, you need to either delete the database that is using those physical files or add a MOVE clause into your RESTORE statement. For the latter, it would look something like this:
RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE,
move 'BBCon' to 'c:\temp\BBCon.mdf',
move 'BBCon_log' to 'c:\temp\BBCon_log.ldf';

How to refresh database through c sharp coding in dot net

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

Categories

Resources