vb.net 코드로 SQL Server 데이터베이스를 만드는 방법
-
21-12-2019 - |
문제
VB 2012 및 SQL Server 2012 Localdb를 사용하고 있습니다.
데이터베이스 파일(.mdf
) 내 폴더에 C:\AppData
예.DB 파일 이름 0105.mdf
& 로그 파일 이름 0105.ldf
누구든지 절차를 알려주실 수 있나요?
연결 문자열을 사용하여 SQL Server 2012 localdb에 연결할 수 있습니다.
Data Source=(LocalDB)\v11.0;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30
해결책 2
고마워요 스티브 페티퍼
다음은 작동한 최종 코드입니다.
Dim Conn As New SqlConnection("Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True")
Using Conn
Conn.Open()
Dim cmd As SqlCommand = Conn.CreateCommand
Dim str As String = "CREATE Database {0} ON (Name= N'{0}', FileName='{1}\{0}.mdf')"
cmd.CommandText = String.Format(str, T2.Text, T1.Text)
cmd.ExecuteNonQuery()
End Using
T1.텍스트:폴더 위치 t2.text :확장자가 없는 파일 이름
다른 팁
SqlCommand.ExecuteNonQuery 사용
Imports System.Data.SqlClient
Dim queryString As String = "CREATE DATABASE [0105] ON PRIMARY (NAME = N'0105', FILENAME = N'C:\APPDATA\Pluto_Data.MDF' , SIZE = 1024KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) " & _
"LOG ON (NAME = N'0105_Log', FILENAME = N'C:\APPDATA\0105_Log.LDF' , SIZE = 1024KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )"
Using connection As New SqlConnection(queryString)
Dim command As New SqlCommand(queryString, connection)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
파일 그룹, 파일 증가, 초기 크기 등과 같이 위에서 변경해야 하는 비트만 변경하면 됩니다.시도해 볼 수 있는 LocalDB가 없기 때문에 작동할 것이라고 생각합니다. 그래서 약간 벗어난 것일 수도 있습니다.
편집하다: 나는 T-SQL을 사용하면서 코스를 벗어나 너무 자유롭고 쉬웠습니다.
대신 아래 댓글에 추가한 링크에서 이것을 시도해 보세요.
Public Function CreateDatabase(ByVal dbName As String, ByVal dbFileName As String) As Boolean
Try
Dim connectionString As String = String.Format("Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True")
Using connection As New SqlConnection(connectionString))
connection.Open()
Dim cmd As SqlCommand = connection.CreateCommand()
DetachDatabase(dbName)
cmd.CommandText = String.Format("CREATE DATABASE {0} ON (NAME = N'{0}', FILENAME = '{1}')", dbName, dbFileName)
cmd.ExecuteNonQuery()
End Using
If (My.Computer.FileSystem.FileExists(dbFileName)) Then
Return True
Else
Return False
End If
Catch
Throw
End Try
End Function
제휴하지 않습니다 StackOverflow