Question Connecting to SQL Server from a command line

njsokalski

Well-known member
Joined
Mar 16, 2011
Messages
102
Programming Experience
5-10
I have an SQL Server database to which I want to connect to from a command line so that I can enter SQL statements. I know the connection string, so I can connect from within Visual Studio 2010 and my web application, but I am having trouble connecting from a command line. I don't care whether I use the Visual Studio command prompt or some other command prompt, but I want to be able to enter SQL statements from a command prompt. How do I do this? Thanks.
 
It's not clear what you're actually asking for. Are you saying that you want to create a Console app so that the user can modify the database or are you saying that, during development, you want to be able use a commandline tool to modify your database? If it's the former, connection is no different to any other project type: use a SqlConnection. If it's the latter then it's nothing to do with VS. You would need to open a command prompt and run either OSQL or, preferably, SQLCMD. They are the old and new SQL Server command line tools. I'm not sure whether they can handle databases that were added directly to a project and are not permanently attached though. In fact, I'm sure that OSQL can't but SQLCMD may be able to.
 
It's the second, I want to access my database through a command line during development. I have tried SQLCMD, but am obviously doing something wrong, because I can't get it to connect, and I am unfamiliar with OSQL. I don't know which command line arguments I need for SQLCMD, but the variables included in my connection string (which are enough to let me connect using that) are:

Data Source
Initial Catalog
Persist Security Info
User ID
Password
Connect Timeout
Encrypt
Network Library
Packet Size
Workstation ID

So I don't know if there is a way to translate this into command line arguments for SQLCMD, because I've been unable to get it to work, and like I said, I'm not familiar with OSQL (actually, I don't even know where to access it or download it or wherever it comes from), so if you have any suggestions, I would greatly appreciate it. Thanks.
 
Back
Top