Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ADO.NET & Database » Creating a SQL Server database programmatically using VB.NET

Creating a SQL Server database programmatically using VB.NET

In this application, I’ll create a SQL Server database, create a database table, add data to it, create database objects such as views, stored procedures, rules, and index and view data in the data grid using Sql data provider.

Author Rank:
Technologies: .NET 1.0/1.1, ADO.NET,Visual Basic .NET
Total downloads :
Total page views :  147001
Rating :
 3.89/5
This article has been rated :  9 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor


Related EbooksTop Videos

SQL not only let you select, add, and delete data from databases table, it also provides commands to manage databases. Using SQL statements you can create database objects programmatically such as a table, view, stored procedure, rule, index and so on. It also provides commands to alter a database and database schemas for example adding and deleting a column from a database table, adding some constraints to a column and so on. This example shows you how to create a new database table, add data to it, create a view of the data, alter database table and then delete the newly created table.

In this application, I'll create a SQL Server database, create a database table, add data to it, create database objects such as views, stored procedures, rules, and index and view data in the data grid using Sql data provider.

To test this application, create a Widows application add a data grid control and some button controls. You can even test code by adding only one button or one button for each activity. Our application form looks like Figure 1.


Figure 1. Creating a database and it's object application.

After adding controls, add the following variables in the beginning of the form class.

Private ConnectionString As String = "Integrated Security=SSPI;" + "Initial Catalog=;" + "Data Source=localhost;"
Private reader As SqlDataReader =
Nothing
Private
conn As SqlConnection =
Nothing
Private
cmd As SqlCommand =
Nothing
Private
AlterTableBtn As
System.Windows.Forms.Button
Private sql As String =
Nothing
Private
CreateOthersBtn As
System.Windows.Forms.Button
Private button1 As System.Windows.Forms.Button

First thing I'm going to do is create ExecuteSQLStmt method. This method executes a SQL statement against the SQL Sever database (mydb which I will create from my program) using Sql data providers using ExecuteNonQuery method. The ExecuteSQLStmt method is listed in Listing 1.

Private Sub ExecuteSQLStmt(ByVal sql As String)
' Open the connection
If conn.State = ConnectionState.Open
Then
conn.Close()
End
If
ConnectionString = "Integrated Security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=localhost;"
conn.ConnectionString = ConnectionString
conn.Open()
cmd = New
SqlCommand(sql, conn)
Try
cmd.ExecuteNonQuery()
Catch ae As
SqlException
MessageBox.Show(ae.Message.ToString())
End
Try
End
Sub
'ExecuteSQLStmt

Listing 1. The ExecuteSQLStmt method.

After this I'm going to create a new SQL Server database. The CREATE DATABASE SQL statement creates a database. The syntax of CREATE DATABASE depends on the database you create. Depending on the database type, you can also set values of database size, growth and file name. Listing 2 creates a SQL Server database mydb and data files are stored in the C:\\mysql directory.

'This method creates a new SQL Server database
Private Sub CreateDBBtn_Click(ByVal sender As Object, ByVal e As
System.EventArgs)
' Create a connection
conn = New
SqlConnection(ConnectionString)
' Open the connection
If conn.State <> ConnectionState.Open
Then
conn.Open()
End
If
Dim sql As String
= "CREATE DATABASE mydb ON PRIMARY" + "(Name=test_data, filename = 'C:\mysql\mydb_data.mdf', size=3," + "maxsize=5, filegrowth=10%)log on" + "(name=mydbb_log, filename='C:\mysql\mydb_log.ldf',size=3," + "maxsize=20,filegrowth=1)"
ExecuteSQLStmt(sql)
End Sub
'CreateDBBtn_Click

Listing 2. Creating a SQL Server database.

Now next step is to create a table. You use CREATE TABLE SQL statement to create a table. In this statement you define the table and schema (table columns and their data types). Listing 3 creates a table myTable with four column listed in Table 1.

Column Name Type Size Property
myId integer Primary Key
myName char 50 Allow Null
myAddress char 255 Allow Null
myBalance float 8 Allow Null

Table 1. New table myTable schema.

Private Sub CreateTableBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Open the connection
If conn.State = ConnectionState.Open
Then
conn.Close()
End
If
ConnectionString = "Integrated Security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=localhost;"
conn.ConnectionString = ConnectionString
conn.Open()
sql = "CREATE TABLE myTable" + "(myId INTEGER CONSTRAINT PKeyMyId PRIMARY KEY," + "myName CHAR(50), myAddress CHAR(255), myBalance FLOAT)"
cmd = New
SqlCommand(sql, conn)
Try
cmd.ExecuteNonQuery()
' Adding records the table
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) " + "VALUES (1001, 'Puneet Nehra', 'A 449 Sect 19, DELHI', 23.98 ) "
cmd = New
SqlCommand(sql, conn)
cmd.ExecuteNonQuery()
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) " + "VALUES (1002, 'Anoop Singh', 'Lodi Road, DELHI', 353.64) "
cmd = New
SqlCommand(sql, conn)
cmd.ExecuteNonQuery()
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) " + "VALUES (1003, 'Rakesh M', 'Nag Chowk, Jabalpur M.P.', 43.43) "
cmd = New
SqlCommand(sql, conn)
cmd.ExecuteNonQuery()
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) " + "VALUES (1004, 'Madan Kesh', '4th Street, Lane 3, DELHI', 23.00) "
cmd = New
SqlCommand(sql, conn)
cmd.ExecuteNonQuery()
Catch ae As
SqlException
MessageBox.Show(ae.Message.ToString())
End
Try
End
Sub 'CreateTableBtn_Click 

Listing 4. Creating a database table.

As you can see from Listing 5, I also add data to the table using INSERT INTO SQL statement.

The CREATE PROCEDURE statement creates a stored procedure as you can see in Listing 10-18, I create a stored procedure myPoc which returs data result of SELECT myName and myAddress column.

Private Sub CreateSPBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
sql = "CREATE PROCEDURE myProc AS" + " SELECT myName, myAddress FROM myTable GO"
ExecuteSQLStmt(sql)
End Sub 'CreateSPBtn_Click

Listing 5. Creating a stored procedure programmatically.

Now I show you how to create views programmatically using CREATE VIEW SQL statement. As you can see from Listing 6, I create a view myView which is result of myName column rows from myTable.

Private Sub CreateViewBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
sql = "CREATE VIEW myView AS SELECT myName FROM myTable"
ExecuteSQLStmt(sql)
End Sub
'CreateViewBtn_Click

Listing 6. Creating a view using CREATE VIEW

The ALTER TABLE is a useful SQL statement if you need to change your database schema programmatically. The ALTER TABLE statement can be used to add and remove new columns to a table, changing column properties, data types and constraints. The Listing 7 show that I change the database schema of myTable by first change column data type range from 50 to 100 characters and by adding a new column newCol of TIMESTAMP type.  

Private Sub AlterTableBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
sql = "ALTER TABLE MyTable ALTER COLUMN" + "myName CHAR(100) NOT NULL"
ExecuteSQLStmt(sql)
End Sub 'AlterTableBtn_Click

Listing 7. Using ALTER TABLE to change a database schema programmatically.

The new table schema looks like Table 2. 

Column Name Type Size Property
myId integer Primary Key
myName char 50 Allow Null
myAddress char 255 Allow Null
myBalance float 8 Allow Null
newCol timestamp 8 Allow Null

Table 2. MyTable after ALTER TABLE

You can also create other database object such as index, rule, and users. The code listed in Listing 8 creates one rule and index on myTable.

Note: Create Index can only create an index if you don't have an index on a table. Otherwise you will get an error message. 

Private Sub CreateOthersBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
sql = "CREATE UNIQUE CLUSTERED INDEX " + "myIdx ON myTable(myName)"
ExecuteSQLStmt(sql)
sql = "CREATE RULE myRule " + "AS @myBalance >= 32 AND @myBalance < 60"
ExecuteSQLStmt(sql)
End Sub 'CreateOthersBtn_Click

Listing 8. Creating rules and indexes using SQL statement.

The DROP TABLE command can be used to delete a table and its data permanently. The code listed in Listing 9 deletes myTable. 

Private Sub DropTableBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim sql As String = "DROP TABLE MyTable"
ExecuteSQLStmt(sql)
'
End Sub 'DropTableBtn_Click

Listing 9. Deleting table using DROP TABLE.

Now next step is to view data from the table, view and stored procedure. The ViewDataBtn_Click method listed in Listing 10 shows the entire data from the table. The ViewSPBtn_Click and ViewViewBtn_Click methods view stored procedure and view data we have created earlier. As you can see using views and stored procedures work same as you use a SQL Statement. We have discussed working with Views and stored procedures in the beginning of this chapter. As you can see from Listing 10, 11, and 12, I view data from stored procedure and view.  

Private Sub ViewDataBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'/ Open the connection
If conn.State = ConnectionState.Open Then
conn.Close()
End If
ConnectionString = "Integrated Security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=localhost;"
conn.ConnectionString = ConnectionString
conn.Open()
' Create a data adapter
Dim da As New SqlDataAdapter("SELECT * FROM myTable", conn)
' Create DataSet, fill it and view in data grid
Dim ds As New DataSet("myTable")
da.Fill(ds, "myTable")
dataGrid1.DataSource = ds.Tables("myTable").DefaultView
End Sub 'ViewDataBtn_Click

Listing 10. Viewing data from a database table.

Private Sub ViewSPBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'/ Open the connection
If conn.State = ConnectionState.Open Then
conn.Close()
End If
ConnectionString = "Integrated Security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=localhost;"
conn.ConnectionString = ConnectionString
conn.Open()
' Create a data adapter
Dim da As New SqlDataAdapter("myProc", conn)
' Create DataSet, fill it and view in data grid
Dim ds As New DataSet("SP")
da.Fill(ds, "SP")
dataGrid1.DataSource = ds.DefaultViewManager
End Sub 'ViewSPBtn_Click

Listing 11.Using a stored procedure to view data from a table.

Private Sub ViewViewBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Open the connection
If conn.State = ConnectionState.Open Then
conn.Close()
End If
ConnectionString = "Integrated Security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=localhost;"
conn.ConnectionString = ConnectionString
conn.Open()
' Create a data adapter
Dim da As New SqlDataAdapter("SELECT * FROM myView", conn)
' Create DataSet, fill it and view in data grid
Dim ds As New DataSet
da.Fill(ds)
dataGrid1.DataSource = ds.DefaultViewManager
End Sub 'ViewViewBtn_Click

Listing 12.Using a view to view data from a table.

Finally, I create AppExit method which releases the connection and reader objects and I call them from the Dispose method as you can see in Listing 13. 

Protected Overrides Sub Dispose(ByVal disposing As Boolean)
AppExit()
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub 'Dispose
' Called when you are done with the applicaton
' Or from Close button
Private Sub AppExit()
If Not (reader Is Nothing) Then
reader.Close()
End If
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End
Sub 'AppExit

Listing 13. AppExit method

Summary

In this article, you saw how to create a new database and database objects including tables, stored procedures, views and alter tables. You also saw how to delete these object using SQL statements.

 

Added by bradley on 1/30/2008

In using this code with 2005 .net adn sqlexpress I had to change a few things for it to work: 1. Import system.data.sqlclient 2. Change 'localhost' in all the strings to '.\sqlserver' 3. in the 'ExecuteSQLStmt' routine, delete the two lines below: ConnectionString = "Integrated security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=.\SqlExpress;" conn.ConnectionString = ConnectionString Also, if you have Management studio express running, the database will not show up until you hit 'refresh'. Hope this helps someone!

 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mahesh Chand
Mahesh is a software consultant, architect, author, MCP, MVP, and founder of C# Corner. He has over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries including Microsoft, Unisys, Barclay’s, Centocor (J&J), McGraw-Hill, Excelon, PMI, and University of Pennsylvania Hospital. Since year 2000, he is been working with, ASP.NET, SQL Server, C# and .NET. His latest experience and interest is Silverlight, WPF, WCF, XAML and .NET 3.5. If you need any consulting in ASP.NET, AJAX, WPF, WCF, or XAML, contact him at mahesh AT c-sharpcorner DOT com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
creating sql database objects programmatically using vb.netaswathy1/11/2006

sir,

this article is very useful .please publish the continuation of this article

Reply | Email | Delete | Modify | 
loginpageramesh4/20/2006

hello sir

how do we design a loginpage in asp.net using vb.net.on asp.net webpage I wil place two textboxes and twolabels with name of username and password.And two buttons one is submit and another one is register button.

what code we have to write for register button.

and what I   have to do in SQL serverdatabase i e to store the values of username and password.

thank you sir.

Reply | Email | Delete | Modify | 
loginpageramesh4/20/2006

hello sir

how do we design a loginpage in asp.net using vb.net.on asp.net webpage I wil place two textboxes and twolabels with name of username and password.And two buttons one is submit and another one is register button.

what code we have to write for register button.

and we have to do in SQL serverdatabase i e to store the values of username and password.

thank you sir.

Reply | Email | Delete | Modify | 
Sql queryRashad2/2/2007
Is it possible to have a user enter information into a txtbox, and on the button click event, pull certain information from a database based solely upon the information entered?
Reply | Email | Delete | Modify | 
 
 
Re: Sql queryMahesh2/5/2007
Yes it is possible. Please post all non-article related questions on forums by clicking on the Forums link on the header.
Reply | Email | Delete | Modify | 
Crystal Report QuestionMehr2/10/2007
1- we have 2 SQL tables (one contains fields like emp_id, name, designation, section and other emp related info And 2nd table contains emp_id, allowance_name, allowance_amount, deduction_name, deduction_amount) 2- we need a crystal report showing section wise employees 3- single employee data must be in a single row 4- sample report fields can be emp_name, emp-designation, allowance1, allowance2, ..., allowanceN, SumOfAllowances, deduction1, deduction2, ..., deductionN, SumOfDeductions, SumOfAllowances-SumOfDeductions. I deadly need this sum1 plz help
Reply | Email | Delete | Modify | 
Your articleLeifur2/25/2007
Dear Mr. Chand. I found your article EXTREMELY helpful and now I finally have some idea about HOW to manage. I tried many books and many articles but they all lost me in the XML parts, which I try to avoid... Thank you for your article! Leifur, Iceland.
Reply | Email | Delete | Modify | 
Your articleLeifur2/25/2007
Dear Mr. Chand. I found your article EXTREMELY helpful and now I finally have some idea about HOW to manage. I tried many books and many articles but they all lost me in the XML parts, which I try to avoid... Thank you for your article! Leifur, Iceland.
Reply | Email | Delete | Modify | 
 
 
Re: Your articleMahesh2/26/2007
Thanks Liefur. I am glad I was any help.
Reply | Email | Delete | Modify | 
how is possible to select sql data from a table?gir4/16/2007
create table mytable(english varchar(100),amharic Nvarchar(100)) insert into mytable values('pretty',N'konjo') insert into mytable values('nice',N'melkam') then select * from mytable; works fine, select * from mytable where english='nice' this works fine ,but select * from mytable where amharic=N'melkam'; don't work; select * from mytable where amharic='melkam'; don't work. know that amharic is a langauge which has its own alphabet, it is very different from latin alphabets, so how is it possible to select non-english langauges from table in sql server 2000? thanks,
Reply | Email | Delete | Modify | 
with vb6 ?bin4/30/2007
hello Mr, how to be with vb6?
Reply | Email | Delete | Modify | 
 
 
Re: with vb6 ?Mahesh4/30/2007
With VB 6.0, you will have to use ADO to execute queries. SQL queries will be same. I do not have any code sample for VB 6.
Reply | Email | Delete | Modify | 
thanksnsahar6/21/2007
this article proved to be a good piece of help...need more help about sql n database connectivity do mail me some good piece of advice.. thanks
Reply | Email | Delete | Modify | 
AppreciationMehdi7/8/2007
Thank's. Brief & useful it was.
Reply | Email | Delete | Modify | 
hi Leuwa8/20/2007
I am Nikhil to give how to connaction sql in vb.net i am crating inventary mangmant system but not conaction to sql erroor in fill data
Reply | Email | Delete | Modify | 
 
 
Re: hi Mahesh8/23/2007

Connection string is defined in this article as following:

ConnectionString = "Integrated Security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=localhost;"

Replace localhost with your server name and mydb with your database. If you are using user id and password, search this site for connection string.

Reply | Email | Delete | Modify | 
 
Re: Re: hi duain9/30/2007

Hi!

I want to create the database only when the database doesn´t exists. How can i verify if the database already exists in the computer? In vb.net

Thanks!

Reply | Email | Delete | Modify | 
sql queryjason12/19/2007
a great article.....it helps a lot....thank u..... may i just ask if how can i search in a database....sample program pls!!
Reply | Email | Delete | Modify | 
hello sirasgar1/14/2008
i have just started with asp.net i have created table with field as name roll sub month.. i want to dispaly data in grid as per the roll no selected by drop down list... can u provide me code
Reply | Email | Delete | Modify | 
A Few Things to addbradley1/30/2008
In using this code with 2005 .net adn sqlexpress I had to change a few things for it to work: 1. Import system.data.sqlclient 2. Change 'localhost' in all the strings to '.\sqlserver' 3. in the 'ExecuteSQLStmt' routine, delete the two lines below: ConnectionString = "Integrated security=SSPI;" + "Initial Catalog=mydb;" + "Data Source=.\SqlExpress;" conn.ConnectionString = ConnectionString Also, if you have Management studio express running, the database will not show up until you hit 'refresh'. Hope this helps someone!
Reply | Email | Delete | Modify | 
 
 
Re: A Few Things to addMahesh2/27/2008
Thanks Bradley.
Reply | Email | Delete | Modify | 
get SQL Server InstanceHardey2/24/2008
How do i get SQL server instance(s) running on my network from vb6 environment or VB2005 IDE? aishupor@yahoo.com
Reply | Email | Delete | Modify | 
With Accessrikita3/11/2008
I had used the same code to create the database inaccess, But it wasn,t work. Can u tell me what changes i have to make in coding?Thanks in advance
Reply | Email | Delete | Modify | 
 
 
Re: With AccessMahesh4/6/2009

Are you getting any errors? Did you try to debug your code and see where and what the problem is? I would look for permissions also. Make sure you use Admin user id and pwd.

Reply | Email | Delete | Modify | 
Help me Dear sir saket3/13/2008
hi Dear sir i m facing some problem please help me (1)How can display hierarchical xml file data into datagridview using vb.net/c#.net window based please send me full program (2) how can transfer single or all tables of ms sql server database into ms access database send me full programe my Email dwivedi_saket@rediffmail.com dwivedi_saket@yahoo.coin
Reply | Email | Delete | Modify | 
how is your experience in IT field now(2008)kala3/26/2008
Dear sir article is very useful sir.Please publish your article continue sir.any comments send my mail:sasik84@gmail.com,sasi_thiyagarajan2007@yahoo.com.
Reply | Email | Delete | Modify | 
1.what is mapping? 2.database repeatly,so i need source code in .NET(vb&asp) prevent the database repeat. kala3/26/2008
Dear sir help me sir.i get a job in IT field.i have finished m.sc IT,help the .NET Q&A,vb,asp,ado.c# etc send reply my mail address sasik84@gmail.com
Reply | Email | Delete | Modify | 
 
 
Re: 1.what is mapping? 2.database repeatly,so i need source code in .NET(vb&asp) prevent the database repeat. Mahesh4/7/2009
This is a good start. Read more articles and tutorials on this site, participate on forums and blogs and ask any questions you have.

Good luck!
Reply | Email | Delete | Modify | 
Create Database Programmaticallybravo65912/2/2008
I like to let you know that your tutorials are great. But there is a problem that I am having with your tutorial on how to create a database programmatically in VB.Net. I created a new application and called is TestDB. Then I also dropped two buttons CreateDB and Create Table both buttons named btnCreateDB and btnTable and a DataGridView to retrieve the database data. When I ran the application and clicked on the CreateDB button nothing happened and then the Create Table nothing happened. I opened sql server to see if the database and the tables were created nothing did. I think this is a good tutorial creating a database programmatically I like to learn how to do that. But is not working for me. Is there something that I am doing wrong. I mean I copy and pasted and changed the naming convention in the button controls. I did emailed you and sorry if I caused any problems it won't happen again. I appreciate for your feedback.
Reply | Email | Delete | Modify | 
HELLO Sirsai ganesh1/20/2009
Dear sir, Thanks for your article.it is extremely good. I have a problem now , please help me for that. problem details: How to create a polyline feature from pixel coordinates (x & y) extracted from an image. first we have to convert pixel coordinates (x & y) to latitude/longitude coordinates called as geo coordinates.Then convert these latitude/longitude coordinates to polyline feature. please help me for this in VB.Net
Reply | Email | Delete | Modify | 
 
 
Re: HELLO SirMahesh4/6/2009
You may want to post your question on C# Corner forums. There are many experts there.
Reply | Email | Delete | Modify | 
"Database 'mydb' already exists" messageCory6/17/2009
Hi Mahesh, this tutorial has been very helpful, so thanks for your work.  I do have one question though.

When I run this program through the first time, everything works as expected.  However, when I launch the program a second time, and click the "Create DB" button, I get a SQL Exception message saying "Database 'mydb' already exists.  Choose a different database name."  Similarly, when I click "Create Table", I get a message saying "There is already an object named 'myTable' in the database."

This occurs even if I delete the files stored in the C:\\mysql directory.  I cannot see the "mydb" database or the "myTable" data connected to my project within Visual Studio, or located in the project folder on my hard drive.  However, I know the data resides somewhere, because when I click "View Table", the correct information is still displayed.

So, that is my question: in what file location is the "mydb" database (and its associated "myTable" table) created?  What is the relationship between this "real" data location, and the data that was saved to the C:\\mysql directory?  Any explanation regarding what data is being created by the "Create DB" routine, and where it is being stored on my machine, would be a great help.

Thanks again!

PS -- In case it helps, I'll also share a little information about my connection string.  The only way I could get the program working was to add a blank database (called "Database1.mdf") to my project from within Visual Studio.  After doing this I was given a connection string of: Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True

The full expanded version of this string is: Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Documents and Settings\cspicer\My Documents\Visual Studio 2008\Projects\CreateDBTest2\CreateDBTest2\Database1.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True

Once I put the first connection string (containing the "Data Directory" shortcut for the full file path), the program worked correctly other than the problems I am asking about above.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved