I am trying to make a database application. I added local database from
add > new item > local database.sdf
In Server Explorer, I created a table in the database. But I am having trouble connecting to it.
I want to show all the data in a DataGrid.
My code:
string ConnectionString = #"Data Source=""c:\users\asus\documents\visual studio 2012\Projects\WpfApplicationLocalDB\WpfApplicationLocalDB\LocalDB.sdf""";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
List<DataRow> lis = dt.AsEnumerable().ToList();
DataGridView.ItemsSource = lis;
But when I build it, Visual Studio finds conn.open(); error. A message says that
SqlException was unhandled by user
Please help...
Also, can anyone suggest a tutorial of how can I create a simple database application in C#? Please help.
If you're using a .sdf file, you're using Microsoft SQL Server Compact Edition (SQL Server CE).
When using SQL Server CE, you must use SqlCeConnection and SqlCeCommand classes - not SqlConnection and SqlCommand (those are for the "full", server-based versions of SQL Server)
Related
I am creating a C# WinForms Application along with SQL LocalDB. I am new to SQL and I am following this tutorial (timestamp: 5.50) to add database in project. I have also added a setup project to install the application to other PCs. When I installed the project for the first time it worked perfectly well, but when I updated the database schema (added one more column) the changes are not reflecting, updated version of setup & assembly and installed the setup file again, the database schema changes are not reflecting in the application. It is giving the following error:
My code is something like this:
private void load_list()
{
string conn = Properties.Settings.Default.dbAgeConnectionString;
SqlConnection sqlConn = new SqlConnection(conn);
string sqltext = "SELECT Name, Age, DOB from Users";
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqltext,sqlConn);
adapter.Fill(table);
sqlConn.Close();
lstRecords.DisplayMember = "Name";
lstRecords.ValueMember = "Id";
lstRecords.DataSource = table;
gvrecords.DataSource = table;
}
Connection String:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbAge.mdf;Integrated Security=True
I tried adding the database files manually in Application folder of Setup but still no results.
I searched on the internet but did not find any database version control or upgrade method for SQL LocalDB. Is there any way I can achieve this?
Thanks in advance.
I am attempting to synchronizing tables in two different .MDF files. After successfully creating a datatable for the first file I get an error when trying to create the second:
Cannot attach file 'E:\JVT-Inventory.mdf' as database 'JVT-Inventory' because this database name is already attached with file 'C:\Database\JVT-Inventory.mdf'
I have created separate procedures for each connection to create the tables then disposed the connection. Both the datatable and adapter are global variables to be used in my routines to compare the tables. None of the online research seems to apply to what I am trying to accomplish.
string conString;
conString = "Data Source=(LocalDB)\\v11.0;attachdbfilename=" + #txtPath.Text + ";Initial Catalog=JVT-Inventory;integrated security=True";
using (SqlConnection connection = new SqlConnection(conString))
{
daRemote = new SqlDataAdapter("SELECT * FROM tblProduct ORDER BY keyPartNo", connection);
SqlCommandBuilder cbRemote = new SqlCommandBuilder(daRemote);
daRemote.Fill(dtRemote);
connection.Dispose();
This connection is made to a file on a flash drive.
The issue appears to be that the MDF file remains open until I exit the application. My question now is, how do I close the MDF file from within my application?
After searching many articles about working with databases I figured out the follow:
SqlConnection cnRemoteBye = new SqlConnection();
SqlCommand cmdRemoteBye = new SqlCommand();
cnRemoteBye.ConnectionString = #"Data Source=(LocalDB)\v11.0;Integrated Security=True";
cmdRemoteBye.CommandText = "ALTER DATABASE [JVT-Inventory] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [JVT-Inventory]";
cmdRemoteBye.Connection = cnRemoteBye;
cnRemoteBye.Open();
cmdRemoteBye.ExecuteNonQuery();
cnRemoteBye.Close();
I am new to C# and SQL Server 2014 Express and I am using Windows forms.
I am building the small application which read/write from/to SQL Server database.
I am trying to automatically attach SQL Server database, then read data from a table named Test_Table and then fill a Datagridview.
The code I used:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand MyCommand= new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter= new SqlDataAdapter();
private void button1_Click(object sender, EventArgs e)
{
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM Test_Table ";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
dataGridView1.DataSource = DataTable;
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
App.config:
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=localhost; AttachDbFilename=D:\\DB\\MyDB.mdf;Integrated Security=True"/>
</connectionStrings>
When I click on button1 it throws an error:
An attempt to attach an auto-named database for file D:\DB\MyDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I have no other databases attached and the database path is correct.
I had a look here, here and here but non of them helped.
Any idea how can I automatically attach a SQL Server database file? Thank you
What is the version of SQL Server are you using? This will explain a lot about your error message.
Your Connection String:
"Data Source=localhost; AttachDbFilename=D:\DB\MyDB.mdf;Integrated
Security=True"
You can only use AttachDbFilename with SQL Express. In your connection string, the Data Source is set to localhost. That sounds like you have a full version SQL Server installed.
If you have a full version of SQL Server installed, you can only attach a database via Management Studio.
If you are using SQL Express, change your data source:
Data Source=.\SQLEXPRESS
Firstly, For Those who would like to ask WHY on earth am I DOWNSIZING from SQL SERVER to ACCESS, let me tell you the scenario.
There are some PC's with very low configuration, (256 MB RAM, 2GHzProcessor) I cannot install SQL Server. Hence I want major operations to carry out on SQL server and some data retrieving and auditing work to be done on Slower machine.
So here we go:
I want to copy table from SQL Server to MS Access 2007. I tried:
1)Connect to sql server, fill a datatable object by reading table from sql server.
2) Create a connection to MS Access, and use Dataadapter.Update method to update table to MS Access database.
However 2nd step is not working although its not throwing any error. Here is my code:
SqlConnection cnn = new SqlConnection(#"initial catalog=DBTempleERM;user id=aditya;password=Aditya_ravi$;Data Source=adityalappy\sqlexpress");
SqlCommand cmd = new SqlCommand("SELECT * FROM donationdetails", cnn);
cnn.Open();
System.Data.SqlClient.SqlDataAdapter sDA = new SqlDataAdapter(cmd);
DataTable donationdetails = new DataTable();
sDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
sDA.Fill(donationdetails);
MessageBox.Show(donationdetails.Rows.Count.ToString());
OleDbConnection oleConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=Aditya_ravi$;Data Source=C:\dbt.accdb");
oleConn.Open();
OleDbCommand oleComm = new OleDbCommand();
OleDbDataAdapter oDA = new OleDbDataAdapter(oleComm);
OleDbCommandBuilder oCb = new OleDbCommandBuilder(oDA);
oDA.Update(donationdetails);
No error is thrown at the end of the execution, but I cannot see any records copied from SQL Server to MS Access.
I learnt that SQL Bulk copy cannot be used to copy from SQL Server to Access.
I also want to add the primary key from SQL Server table to MS Access table.
Why dont you use SSIS to do this for you.
You can create a SSIS package to copy a sql table to MS access.
If you want to initiate by .NET then create a SSIS package and call it from .NET
For details
At this point, oDA is not connected to any table on the Access side:
oDA.Update(donationdetails);
So even though you have all the data in a DataTable, you haven't got a target to copy it into.
I don't think this is the best approach, but that's the core of why your code isn't working as it is.
Ancient question, but I'm betting the RowState of all your rows in donationdetails were Unchanged, so the DataAdapter treats them as "I don't need to do anything with this row."
You can use dataset object instead of datatable.
DataSet ds=new DataSet();
sDA.Fill(ds,tablename);
oDA.Update(ds);
I am working with C# windows application
and I am facing a problem with OLEDB connection to SQL SERVER 2008
my code is too simple:
I am trying to fill the datagridview from this query
string connString = "Provider=SQLOLEDB;Data Source=servername;Initial Catalog=DBname;Integrated Security=SSPI";
string query = "SELECT * FROM account";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
//the DataGridView
//DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView_FraudDetails.DataSource = bSource;
dAdapter.Update(dTable);
but I get the Following error in this line
//fill the DataTable
dAdapter.Fill(dTable);
"[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied."
The code was running well , but when I uninstalled the server and reinstalled it again it gave me that error
I tried to turn off the firewall but it doesn't work
any suggestion please
Are you using SQL Server Express? If so you need to make sure that it is configured to accept connections via either TCP/IP or named pipes. By default, SQL Server Express does not accecpt connections. See http://www.datamasker.com/SSE2005_NetworkCfg.htm (this page is specific to SQL Server 2005 but should apply to 2008 as well).
Go to SQL Server Configuration Manager (under All Programs > Microsoft SQL Server in start menu) and for your instance, make sure TCP/IP is enabled. It is disabled by default for a new install of SQL Server.