ExecuteNonQuery of insert function fired successfully but database doesn't update - c#

I try to insert data into my database, all operations are done successfully but database does not update after the SQL query was executed. It is windows based application. I put the connection string in app.config file.
When I run this application code. and insert the data it show me the msg "Data inserted", but when I check the database there no data updated in database.... give me some solution.
I use Visual Studio 2013 and SQL Server 2012.
Here is my code:
namespace Sample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString.ToString());
sqlcon.Open();
string str = "insert into tab(name,pwd) values('" + textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(str, sqlcon);
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted");
cmd.Clone();
}
catch(Exception E)
{
MessageBox.Show("No data inserted");
}
}
}
}
App.config
<configuration>
<connectionStrings>
<add name="cons"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\Database1.mdf';Integrated Security=True"/>
</connectionStrings>
</configuration>

hey i solve this problem myself
i just replace the full path in connection string with (|DataDirectory|\Database.mdf).... like this
<configuration>
<connectionStrings>
<add name="cons" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\Dhaval\documents\visual studio 2013\Projects\Sample\Sample\Database.mdf';Integrated Security=True"/>
</connectionStrings>
</configuration>
so the connection string access right database of application.. not(.\bin\debug) "Database.mdf" file..

Firstly, to prevent injection attacks and to avoid syntax errors, use parameters. Secondly, to ensure resources are properly disposed of, use the "using" statements. Thirdly, show the error message thrown. The following (untested) code illustrates these techniques. Also, what is the cmd.Clone() used for?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString.ToString());
try
{
using (sqlcon)
{
sqlcon.Open();
string str = "insert into tab(name,pwd) values(#Value1, #Value2)";
using (SqlCommand cmd = new SqlCommand(str, sqlcon))
{
cmd.Parameters.Add(new SqlParameter("Value1", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("Value2", TextBox2.Text));
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted");
//cmd.Clone();
}
}
}
catch (Exception E)
{
throw new Exception(E.Message);
}
finally
{
sqlcon.Close();
}
}

Related

Visual Studio - Unable to view table data

I am writing a report manager program. I created a database from project -> new item -> service-based database. When I attempt to insert I am not getting an error. When I attempt to view the data in the database with Server Explorer -> Reports -> Show Table Data I'm getting an empty table. Upon refresh, I get this error
database cannot be imported. It is either an unsupported SQL server
version or an unsupported database compatibility.
My code
private void btnSubmit_Click(object sender, EventArgs e)
{
string span = cbSpan.Text;
string reportData = tbReportInput.Text;
DateTime timeStamp = DateTime.Now;
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\App_Data\\ReportsDB.mdf;Integrated Security=True");
if (tbReportInput.Text == string.Empty)
{
MessageBox.Show("Report must have text!!!!");
}
else
{
try
{
string sqlQuery = "INSERT INTO dbo.Reports(TimeSpan, ReportData, TimeStamp) " +
"VALUES (#TimeSpan, #ReportData, #Date)";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("#TimeSpan", span);
cmd.Parameters.AddWithValue("#ReportData", reportData);
cmd.Parameters.AddWithValue("#Date", timeStamp);
con.Open();
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
MessageBox.Show(i + " Data Saved");
}
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
My connection string from app.config
<connectionStrings>
<add name="ReportManager.Properties.Settings.ReportsDBConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\App_Data\ReportsDB.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Try connecting to the database from sql server Managment studio, seems like a version conflict in visual studio.

Unable to insert values in sql server local db using c#

I'm unable to insert data into table. we are using local db. I'm not even getting any exception
string constr = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("insert into Client_Name(Name) values('" + textBox1.Text + "')",con);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
Console.Write("Exception");
}
}
In app.config
<connectionStrings>
<add name="server" connectionString="Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Integrated
Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
I have tried all the possible way, and got the best solution considering your scenario.
During an hour observation got to know due database connection
persistence issue you were having that problem try below snippet would
work as expected.
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Connect Timeout=30;Integrated Security=True;";
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("Insert into [LocalTestTable] values (#name,#description)", _connection))
{
command.Parameters.AddWithValue("#name", "TestFlatName");
command.Parameters.AddWithValue("#description", "TestFlatDescription");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Hope that will resolve your problem without having anymore issue.

how to backup and restore mdf file in winform C# after deployment project?

I am developing a desktop application in c# visual studio 2013, where I want to create a feature in which a user is allowed to restore and backup the Database by itself. but problem is that it doesn't backup or restore database after deploy project.
When I try to Backup it says!
Database 'DatabaseName' does not exit.Make sure the name is entered correctly.
BACKUP DATABASE is terminating abnormally.
When I try to Restore Database it says
System.Data.Sqlclient.SqlException (0x80131904): User does not have permission to alter database .mdf', the database does not exit, or the the database in not in a state that allows access checks. and so on!
I am using SQL Server Express 2012 by attaching mdf file to the application, when i try to backup using query it works when i add Connection String through SQL Server but after attach mdf file i won't work .
have watch some tutorial videos and figured out some codes but I got nothing
here is my BACKUP code!
private void buttonbackup_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\neyadatabase.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
String sql = "BACKUP DATABASE neyadatabase TO DISK = '" + backuploca.Text + "\\neyadatabase - " + DateTime.Now.Ticks.ToString() + ".Bak'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show("backup done successfully!");
con.Close();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and here is my RESTORE Code!
private void buttonrestore_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\neyadatabase.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
string sqlStmt2 = string.Format("ALTER DATABASE [neyadatabase.mdf] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE [neyadatabase.mdf] FROM DISK='" + restoreloca.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [neyadatabase.mdf] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successefully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I am a beginner in this if anyone is going to help me please give some example too so that I can better understand!
Thank you
For backup use :
private void buttonbackup_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConn = new SqlConnection())
{
dbConn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=neyadatabase;Integrated Security=True;Connect Timeout=30;";
dbConn.Open();
using (SqlCommand multiuser_rollback_dbcomm = new SqlCommand())
{
multiuser_rollback_dbcomm.Connection = dbConn;
multiuser_rollback_dbcomm.CommandText= #"ALTER DATABASE neyadatabase SET MULTI_USER WITH ROLLBACK IMMEDIATE";
multiuser_rollback_dbcomm.ExecuteNonQuery();
}
dbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = yourConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = new SqlCommand())
{
backupcomm.Connection = backupConn;
backupcomm.CommandText= #"BACKUP DATABASE neyadatabase TO DISK='c:\neyadatabase.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And for restore :
private void buttonrestore_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection restoreConn = new SqlConnection())
{
restoreConn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=neyadatabase;Integrated Security=True;Connect Timeout=30;";
restoreConn.Open();
using (SqlCommand restoredb_executioncomm = new SqlCommand())
{
restoredb_executioncomm.Connection = restoreConn;
restoredb_executioncomm.CommandText = #"RESTORE DATABASE neyadatabase FROM DISK='c:\neyadatabase.bak'";
restoredb_executioncomm.ExecuteNonQuery();
}
restoreConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Backup and restore bak file. Mdf/ldf is for attaching not backup.
I hope this helps you.
If you faced any problem let me know to update my answer ;). Good luck

must declare the scalar variable #TextBox1 asp.net

this is the part of the code that i am sharing for the solution of my new application.
when i execute this code,it throws exception "Must declare the scalar variable #textBox1"
public partial class About : Page
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = "Data Source=.;Initial Catalog=carpro;Integrated Security=True";
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Insert into Driver_Registration(Driver_Name,Driver_DOB,Driver_Address,License_Number,National_Insurance_Number,"+
"Email_Address,UK_History,Contact,Occupation,License_Details,Taxi_License_Number,"+
"Deposit_Details,Weekly_Rent) Values (#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5," +
"#TextBox6,#TextBox7,#TextBox8,#TextBox9,#TextBox10,#TextBox11,#TextBox12,#TextBox13)",con);
cmd.Parameters.AddWithValue("#Driver_Name",TextBox1.Text);
cmd.Parameters.AddWithValue("#Driver_DOB", TextBox2.Text);
cmd.Parameters.AddWithValue("#Driver_Address", TextBox3.Text);
cmd.Parameters.AddWithValue("#License_Number", TextBox4.Text);
cmd.Parameters.AddWithValue("#National_Insurance_Number", TextBox5.Text);
cmd.Parameters.AddWithValue("#Email_Address", TextBox6.Text);
cmd.Parameters.AddWithValue("#UK_History", TextBox7.Text);
cmd.Parameters.AddWithValue("#Contact", TextBox8.Text);
cmd.Parameters.AddWithValue("#Occupation", TextBox9.Text);
cmd.Parameters.AddWithValue("#License_Details", TextBox10.Text);
cmd.Parameters.AddWithValue("#Taxi_License_Number", TextBox11.Text);
cmd.Parameters.AddWithValue("#Deposit_Details", TextBox12.Text);
cmd.Parameters.AddWithValue("#Weekly_Rent", TextBox13.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Registration Successfull";
con.Close();
}
}
The parameters you are using in your INSERT statement are not the same parameters you are creating in your cmd.Parameters.AddWithValue(..). Replace the INSERT parameters to the ones you actually created like #Driver_Name.
Also, you should move your
con.ConnectionString = "Data Source=.;Initial Catalog=carpro;Integrated Security=True";
con.Open();
down to your button. Essentially you are only opening your connection once, then closing it on button click. Currently, there is no way to re-open the connection without re-starting the application.
Or better yet segment it off into its own class/function.
Or even better, setup the connection string in the web.config and call it from there utilizing dependency injection.
in your query you specify the parameters:
(#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5," +
"#TextBox6,#TextBox7,#TextBox8,#TextBox9,#TextBox10,#TextBox11,#TextBox12,#TextBox13)
you have 2 options
1 you can change your query to :
VALUES(#Driver_Name,......
2 you can change you AddWithValue to:
cmd.Parameters.AddWithValue("#TextBox1",TextBox1.Text);
...

Upload a Microsoft Access Database into a Microsoft SQL Server Express Database

I am trying to upload a Microsoft Access Database into a Microsoft SQL Server Express Database.
The structure of the Access and the SQL Database are identical except for the name of the Primary Key.
Error Code:
System.InvalidOperationException: No data exists for the row/column. at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal) at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal) at System.Data.OleDb.OleDbDataReader.get_Item(Int32 index) at ACCESStoMDF._Default.Button1_Click(Object sender, EventArgs e) in C:\Users\path2ACCESStoMDF\ACCESStoMDF\Default.aspx.cs:line 44
web.config
<configuration>
<connectionStrings>
<add name="ACCESSdb"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\path1\DBaccess.accdb;Persist Security Info=False;" />
<add name="MSSQLdb"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MSSQLdb.mdf;User Instance=true;"
providerName="System.Data.SqlClient" />
</connectionStrings>
MSAccessTOMSSQL.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
String connStr = ConfigurationManager.ConnectionStrings["ACCESSdb"].ConnectionString;
String cmdStr = "SELECT * FROM [TableACCESS];";
try
{
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbCommand cmd = new OleDbCommand(cmdStr, conn))
{
conn.Open();
using (OleDbDataReader dr = cmd.ExecuteReader())
{
String connStr1 = ConfigurationManager.ConnectionStrings["MSSQLdb"].ConnectionString;
String cmdStr1 = "INSERT INTO [Table1] (col1,col2,col3) VALUES (#col1,#col2,#col3);";
try
{
using (SqlConnection conn1 = new SqlConnection(connStr1))
{
using (SqlCommand cmd1 = new SqlCommand(cmdStr1, conn1))
{
conn1.Open();
cmd1.Parameters.AddWithValue("#col1", dr[1]);
cmd1.Parameters.AddWithValue("#col2", dr[2]);
cmd1.Parameters.AddWithValue("#col3", dr[3]);
cmd1.ExecuteNonQuery();
conn1.Close();
cmd1.Dispose();
conn1.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = "Insert Into: " + ex.ToString();
}
}
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = "Access: " + ex.ToString();
}
}
An OleDbDataReader allows you to process the results of a SELECT query row-by-row. As shown in the documentation, you need to do something like
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
reader.Close();
Note also that the numeric index of the returned row is zero-based, so the first column is reader[0].

Categories

Resources