Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
TL;DR so you stop putting this on hold:
Visual Studio will not allow me to create a live connection to a database on an SQL server within a project, even though it can communicate with the server outside of projects. I want it to have a live connection so I can make a website that uses and allows access to the database.
I have Visual Studio 2017 Professional, and Microsoft SQL Server Management Studio 2017.
I have successfully connected a database from the server to Visual Studio such that I can edit the database in Visual Studio, and the server will reflect my changes. However, I cannot get a live connection to the server inside any project. When I import the database into a project, it just creates a copy that does not actually communicate with the server.
I'm thinking I need to create some sort of special object or change some settings in Visual Studio.
Do I need to switch to Enterprise for supported features? It seems rational that the professional edition should be sufficient for this, but if anyone knows how to solve this kind of issue with a different version of Visual Studio or how to create a website connected to a database server through another [hopefully affordable] program, I'm all ears. Thank you!
(This paragraph added later for clarity:) My goal is to create a website using Visual Studio which allows authorized users to edit the database. Unless doing so is a terrible idea, I want to start by making it possible to edit the database on the server using the website made in Visual Studio, and then add the security features. The current database on the server is placeholding junk until the system is satisfactorily set up. It sounds like it may be possible access the database using a website without directly putting it in the Visual Studio project, so I'm looking into the directions provided in the second comment.
The least error-filled solution I managed is as follows, based on #Symon's comment and link. I've tried several things for the first line, and being public void seems to case about 1/30th the errors as being anything else I've tried, which definitely doesn't mean it's actually the right answer. Items in square brackets are removed for security reasons. I entered the credentials for the database exactly as I did in the popup window to connect Visual Studio in general to the database on the server.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public void heresanamespacethingy (string stp)
{
//GET STORED PROCEDURE HERE
string conStr = #"Data Source=[server name]; Initial Catalog=[database name]; User ID=[my user ID]; Password=[my password]";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
The error is
CS0116 A namespace cannot directly contain members such as fields or methods.
I'm using VS Community and can interact with my MS SQL Server just fine. The edition of Visual Studio that you are using isn't going to limit what you can do code-wise. The editions merely add extra features. I have never heard of anyone being limited in their projects because of the edition of Visual Studios that they are using.
As #Kfirprods stated, it may be very helpful for you to manage your Server/Databases with Microsoft SQL Server Management Studio 2017 instead of trying to use Visual Studios for everything.
The most common way that I've seen to get your live/current database information and data is to have your C# code call to the live data and pull it. I will have an example of C# calling a stored procedure below. The example only calls a stored procedure, showing how it is possible for you to use C# to connect to SQL Server and alter data. You can also send individual, inline queries through this method. Though, to avoid SQL injection (especially since it's a website) , it'd be better protection to use this method to call Stored Procedures and Views rather than sending inline queries.
This may be a good link to read up on for learning how to start using C# to connect to SQL Server. It's what I used to get started!
I have my SQL Server Management studio connected to my Server/Databases, and my Visual Studio is only concerned about my C# code. It helps keep things separated and organized (for me, anyway).
Here is a sample of a C# method that connects to a SQL Database, and runs a Stored Procedure:
public void CallSproc(string stp)
{
//GET STORED PROCEDURE HERE
string conStr = "Data Source=" + ConfigurationManager.AppSettings["DataSource"] + "Initial Catalog=" + ConfigurationManager.AppSettings["InitialCatalog"] + "Integrated Security=True;";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
Code Explained:
ConfigurationManager.AppSettings[] points to my App.config file and keys (identifiers) where this data is stored. In case the current server is lost, the program doesn't require a re-compile. The config file just needs altered to point to the right location.
The variable stp is a string that is passed from another method which holds the name of the stored procedure (ex. "stpAddNumbers").
conStr is the connection string that tells the SqlConnection() call what Server and database to connect to.
conn.Open(); opens the connection to the SQL Server itself.
cmd.CommandType = CommandType.StoredProcedure; tells the code that you're calling for a stored procedure.
cmd.ExecuteNonQuery(); executes the stored procedure and the results are returned.
CS0116 A namespace cannot directly contain members such as fields or methods:
With the code you have shown along with the error message, you don't seem to have a namespace at all. To fix this, simply wrap your method in a namespace. Like so:
...
using System.Threading.Tasks;
namespace HeresANameSpace
{
class ThisIsAClass
{
public void HeresAMethod (string stp)
{
//GET STORED PROCEDURE HERE
string conStr = #"Data Source=[server name]; Initial Catalog=[database name]; User ID=[my user ID]; Password=[my password]";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
//End of HeresAMethod()
}
//End of HeresAClass
}
//End of HeresANamespace
}
When starting from a blank Code file, you need to write in the namespace , classs and methods . A method goes inside of a class, a class goes inside of a namespace.
Related
I am trying to conncet access database to my visual studio but i face this type of error "The Microsoft.ACE.OLEDB.12.0" provider is not registered on the local machine.
I look at some solutions on google i got that after downloading Microsoft Access Database Engine on Local machine we are able to connect database.But i still face this problem. So What should i do for it? .And i am using Windows10 but i use Ms office 2007 and my system is 64-bit.enter image description here
You don't mention if you planning to use the x32 bit or x64 version of access.
So, assuming you downloaded the access data engine? You have to choose or decide WHICH bit size version you wish to use.
That download can be found here:
https://www.microsoft.com/en-ca/download/details.aspx?id=13255
And you have two choices:
Ok, next up?
You MUST set and FORCE your project to the correct bit size.
that is this project setting in VS.
So, if you using x32 version, then use x86 version, and if adopting x64 version, then set your project to x64.
So, don't use "any" for your project setting - you have to force the issue.
So, try setting up a connection. You have two choices:
Use the ODBC provider,
or
Use the oleDB provider
So, ok, ODBC? then that connection setting should look like this:
For odbc, the connecton string should look like this:
Driver={Microsoft Access Driver (*.mdb, *.accdb)};
dbq=C:\TEST\test444.accdb;uid=Admin
for oleDB, the connection string should look like this:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\test\test45.accdb
And in both cases, you can as a normal rule, leave the password blank.
Assuming you used the project settings, say here:
(and you can use the connection string builder in above. BUT BE VERY carefull, if you are running access x64, then the test connection WILL ALWAYS ALWAYS fail, since VS is a x32 bit applcation, but if you run your code, and the project was forced to x64 bits, then the connection will work DISPITE VS and the test connection telling you it does not.
So, to use the above ODBC connection, we have this:
using (OdbcConnection conn = new OdbcConnection(Properties.Settings.Default.AccessODBC))
{
string strSQL =
"SELECT * FROM tblHotels ORDER BY HotelName";
using (OdbcCommand cmdSQL = new OdbcCommand(strSQL, conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
dataGridView1.DataSource = rstData;
}
}
And for oledb, we would have this:
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
string strSQL =
"SELECT * FROM tblHotels ORDER BY HotelName";
using (OleDbCommand cmdSQL = new OleDbCommand(strSQL, conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
dataGridView1.DataSource = rstData;
}
}
So, which provider to use?
Most use and suggest oleDB.
However, I think using ODBC is not all that bad of a choice. the reason is you can change the connection to sql server, or other database systems, and NOT have to change your provider, but only the connection string.
While you can sort of do the same with oleDB, there is now MUCH better support for ODBC database systems.
I have a Windows web application and have created a .mdf file in the App_Data folder and I am trying to insert data into the tables already created.
It is able to retrieve codes with a basic SELECT * statement, but I can't insert data, this is the code I have:
private void Update(string username)
{
SqlConnection con = new SqlConnection(#"MYSQLCONNECTION");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string bcd = "INSERT INTO NameList(name) VALUES (#paraUsername)";
cmd = new SqlCommand(bcd, con);
cmd.Parameters.AddWithValue("#paraUsername", username);
cmd.ExecuteNonQuery();
list.Update();
con.Close();
}
This code has worked for me in the past, but this time round it does not work. There is no error shown, but the data is not inserted into the table.
This is how I call the method in side my button_click method:
Update(tbName.text);
What might be the problem?
Assuming you have a
AttachDbFileName=......
section in your connection string - then this is a known issue:
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. YourDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
I am writing code for a small company that is all about purchase and sell. I wrote C# code with using external database (SQL Server 2014), now it's time to make the exe file of that code.
I tried my best but it doesn't work.
How can I connect SQL Server 2014 database files with my application so that when someone installs it on his computer he also got SQL Server connected with that application?
Hi actually we deploy code as setup file (.msi), you can create setup project using Wix or install-shield ( maybe other too,but these two are most popular and widely used)
You can do database deployment in two ways
1.) you can provide SQL script for generating SQL server and give instruction for generating Database from Script. It is simple and easy to do.
2.) Other way is provide option to create database from setup. It need some work, but it is more good way.
Now come to your question, you can provide some UI in setup that take input from user and connect to appropriate DB. Or create a UI for Updating configurations, and save configuration (connection string ) in some file ( ex: .ini or .config file).
Below are the some URL for creating Setup and connecting to Db using Wix:
WIXDataBase
installing-databases-using-wix
Creating-an-installer-using-Wix
using-wix-to-install-sql-databases-and-execute-sql-scripts
WiX Samples
Ideally you'd have a SQL server set up somewhere. If not you'll have to install sql server. In your app it's just a matter of setting up the connection string and running sql commands against it.
string connectionString = "Data Source=server //rest of connection string"
Then in c# you can do
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT TOP 100 * FROM SomeTable", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetString(0), reader.GetString(1), reader.GetString(2));
}
}
}
GetString can be changed to GetInt or whatever the datatable will be. This should be enough information to get you started. If you know the structure of the database its simple to put the results into your classes for the application.
Context
My appliction uses an SQL database from which it reads my datatables at start of my application. If the application would fail to connect to the SQL DB, I have a local Ms Access .MDB file. I have a separate thread that checks if the local database is outdated.
I have a DataTable which I obtain from my SQL connection --> Verified and working
I can connect to my Access database locally and read from it --> Verified and working
Issue/Question
I'm trying to update my local database by updating it with the DataTable I obtained from my SQL Connection.
public static void UpdateLocalDatabase(string strTableName, OleDbConnection MyConnection, DataTable MyTable)
{
try
{
if (CreateDatabaseConnection() != null)
{
string strQuery = "SELECT * FROM " + strTableName;
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
OleDbCommandBuilder MyCommandBuilder = new OleDbCommandBuilder(MyAdapter);
MyAdapter.SelectCommand = new OleDbCommand(strQuery, odcConnection);
MyAdapter.UpdateCommand = MyCommandBuilder.GetUpdateCommand();
MyConn.Open();
MyAdapter.Update(MyTable);
MyConn.Close();
}
}
catch { }
}
If I debug this snippet, all variables are what they should be:
strTableName = the correct name for my table
MyConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyLocation;Persist Security Info=True;JET OLEDB:Database Password=MyPassword;"
MyTable = is the correct table that is also used further on by my application
This process runs through without an error and without using the catch but it does not touch my database, it just doesn't do a thing.
Am I dropping the ball here or just missing the obvious, I have no idea but I browsed many articles and apart for showing the MyAdapter.Update(), there doesn't seem to be much more to it.
Any help is welcome.
Thanks,
Kevin
Does your backup database have to be in access? because if you used SQL Compact Edition it'd be much easier to copy between the two?
Yes, it would either mean attaching it with your installer or just ensuring that all client machines have it pre-installed, it is free however.
if this is an issue then all you need to do (I think, not done it myself)
would be to go to your installer projects properties, click prerequisites and then tick SQL compact so that it will be installed before your application can be used, iv done this before with other frameworks and it just pops up a box with the install shield asking whether they want to download the necessary software and its just one click then it should be done for them.
Do you need a hand on using the compact database also?
One negative by the way is it does lack some higher end features but shouldn't affect average database work
EDIT
if you will be using sql CE you can easily make the databse in VS by clicking data and new data source then following the steps making sure to put sql CE when asked
if it works, you'll end up with an .sdf database
I provided a code snippet that fixed the issue on my related question here: Export SQL DataBase to WinForm DataSet and then to MDB Database using DataSet
We are trying to build a Help Desk ticketing system just for intranet. Deciding upon the ASP .NET (C#) with Visual Studio 2008 Express (think we have a full version floating around if we need it). Nothing fancy, couple of pages grabbing NTLM information, system information and storing it along with their problem in a database. Goal is to make it simple, but instead of using our SQL Server 2000 back end, the admin wants me to use MS Access. I have the GridView and connections running smooth. Can pull select queries until my heart is content. However, tying in a couple variables with a text box on a submit button into say an INSERT statement.. well I don't even know where to begin with MS Access. Every internet example is in VB .NET plus seems to be hand coding what Visual Studio has already done for me in a few clicks.
Is MS Access going to be too hard for all we want to do? If not, where do we begin to simply submit this data into the tables?
Edit: After a bunch of playing around we have the OleDB working. It's not pretty, yes SQL Server would be awesome but, sometimes you just have to play ball.
Edit: Anyone looking for an actual coded answer, here you are. There has got to be others out there in the same boat.
string userIP = Request.UserHostAddress.ToString();
string userDNS = Request.UserHostName.ToString();
string duser = Request.ServerVariables["LOGON_USER"]; //NTLM Domain\Username
string computer = System.Environment.MachineName.ToString(); //Computer Name
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\helpdesk.MDB;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO ticketing ([user], [comp], [issue]) VALUES (#duser, #computer, #col3)";
cmd.Parameters.Add("#duser", OleDbType.VarChar).Value = duser;
cmd.Parameters.Add("#computer", OleDbType.VarChar).Value = computer;
cmd.Parameters.Add("#col3", OleDbType.LongVarChar).Value = TextBox1.Text;
cmd.ExecuteNonQuery();
conn.Close();
The admin is nuts. Access is an in-process database, and as such is not well suited for web sites where users will be creating or updating records.
But as far as creating INSERT queries go, Access is no harder than anything else. If you can't create INSERT queries for Access you'll probably have trouble with SQL Server as well.
I also suggest using SQL Server, but considering your problem:
What is your problem writing an INSERT query for Access ?
You should make use of the classes that you'll find in the System.Data.OleDb namespace:
OleDbConnection
OleDbCommand
Quick'n dirty code (not compiled whatsoever):
OleDbConnection conn = new OleDbConnection (connectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText= "INSERT INTO myTable (col1, col2) VALUES (#p_col1, #p_col2)";
command.Parameters.Add ("#p_col1", OleDbType.String).Value = textBox1.Text;
...
command.ExecuteNonQUery();
There are some caveats with the OleDb classes however (like adding the Parameters to the collection in the order that they occur in your SQL statement, for instance).
Don't bother with Access. Use SQL Server Express. There's also an admin tool for it that looks like the full blown SQL Server management tool.
Access has its place, and can usually do more than what most people give it credit for, but yes you want to use SQL Server in ones of its many forms (eg. SQL Server Express) or another proper "server" database for a web app like this.