Visual Studio - Unable to view table data - c#

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.

Related

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

How to insert data into MySQL database using Asp.net

I am trying to insert data into MYSQL database using Asp.Net but I am getting the following error message: Failed to connect to the database due to System.InvalidOperationsException.The connection must be valid and open.
Here is what I am doing:
protected void SU_Button_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=mno; Database=xyz; User ID=abc; Password=abc";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
try
{
string insertData = "insert into signup_table(firstname,surname,mobile_number,email_address,password," +
"confirm_password) values (#F_Name, #S_Name, #M_Number, #E_Address, #Password, #C_Password)";
MySqlCommand command = new MySqlCommand(insertData, connection);
command.Parameters.AddWithValue("#F_Name",FN_TextBox.Text);
command.Parameters.AddWithValue("#S_Name", SN_TextBox.Text);
command.Parameters.AddWithValue("#M_Number", MN_TextBox.Text);
command.Parameters.AddWithValue("#E_Address", EA_TextBox.Text);
command.Parameters.AddWithValue("#Password", P_TextBox.Text);
command.Parameters.AddWithValue("#C_Password", CP_TextBox.Text);
int result = command.ExecuteNonQuery();
connection.Open();
MessageBox.Show("Connected to database");
MessageBox.Show("Data inserted successfully");
}
catch(Exception ex)
{
MessageBox.Show("Failed to connect to database due to" + ex.ToString());
MessageBox.Show("Failed to insert data due to" + ex.ToString());
}
}
}
Please suggest something. Thanks in advance... :)
You have to open your connection before you execute the query.
connection.Open();
int result = command.ExecuteNonQuery();
also dont forget to close your connecion after you finished.
change this
int result = command.ExecuteNonQuery();
connection.Open();
to this
connection.Open();
int result = command.ExecuteNonQuery();

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

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();
}
}

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].

Error while trying to connect to sql server database from C#.Net

Here is the code
public string connectionString = ConfigurationManager.AppSettings["myconnection"];
public int get_details(string team1_name, string team2_name)
{
SqlConnection con = new SqlConnection(connectionString);
string sql = "insert into Table(team1_name,team2_name) values(#team1_name,#team2_name)";
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.AddWithValue("#team1_name", team1_name);
cmd.Parameters.AddWithValue("#team2_name", team2_name);
try
{
con.Open();
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
Whenever I run this code, the error says
An unhandled exception of type 'System.InvalidOperationException' occurred in dblayer.dll
Additional information: The ConnectionString property has not been initialized.
Can anyone help me out?
Solution 1: You need touse following statement to initilialise the connectionstring properly.
public string connectionString =ConfigurationManager.ConnectionStrings
[ConfigurationManager.AppSettings["myconnection"]].ConnectionString;
Solution 2:
Table is keyword hence you need to enclose it within the square brackets [].
Replace This:
string sql = "insert into Table(team1_name,team2_name)
values(#team1_name,#team2_name)";
With :
string sql = "insert into [Table](team1_name,team2_name)
values(#team1_name,#team2_name)";
Try This:
Connection String:
<configuration>
<connectionStrings>
<add name="conName" connectionString="Server=ServerName;initial catalog=DBName;User ID=sa;Password=sa123;"/> // SQL server Authentication
</connectionStrings>
<configuration>
public string connectionString = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
public int get_details(string team1_name, string team2_name)
{
SqlConnection con = new SqlConnection(connectionString);
string sql = "insert into Table(team1_name,team2_name) values(#team1_name,#team2_name)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#team1_name", team1_name);
cmd.Parameters.AddWithValue("#team2_name", team2_name);
try
{
cmd.Connection = con;
con.Open();
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}

Categories

Resources