Hi nirmal90,
Check this example. Now please take its reference and correct your code.
FormDesign
Namespace
C#
using System.Data.SqlClient;
VB.Net
Imports System.Data.SqlClient
Code
C#
private void button1_Click(object sender, EventArgs e)
{
if (CheckDatabaseExists(textBox1.Text))
{
MessageBox.Show("Database already Created!", "Database Exists", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
CreateDatabase(textBox1.Text);
MessageBox.Show("DataBase is Created Successfully!", "Database Exists", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public static bool CheckDatabaseExists(string dataBase)
{
string conStr = "Data Source=.;Initial Catalog=master;uid=sa;pwd=pass@123;";
string cmdText = "SELECT * FROM master.dbo.sysdatabases WHERE name ='" + dataBase + "'";
bool isExist = false;
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
isExist = reader.HasRows;
}
}
con.Close();
}
return isExist;
}
public void CreateDatabase(string dataBase)
{
string conStr = "Data Source=.;Initial Catalog=master;uid=sa;pwd=pass@123;";
SqlConnection con = new SqlConnection(conStr);
string str = "CREATE DATABASE " + dataBase;
SqlCommand cmd = new SqlCommand(str, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
VB.Net
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
If CheckDatabaseExists(textBox1.Text) Then
MessageBox.Show("Database already Created!", "Database Exists", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
CreateDatabase(textBox1.Text)
MessageBox.Show("DataBase is Created Successfully!", "Database Exists", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Public Shared Function CheckDatabaseExists(ByVal dataBase As String) As Boolean
Dim conStr As String = "Data Source=192.168.0.1\SQL2005;Initial Catalog=master;uid=sa;pwd=pass@123;"
Dim cmdText As String = "SELECT * FROM master.dbo.sysdatabases WHERE name ='" & dataBase & "'"
Dim isExist As Boolean = False
Using con As SqlConnection = New SqlConnection(conStr)
con.Open()
Using cmd As SqlCommand = New SqlCommand(cmdText, con)
Using reader As SqlDataReader = cmd.ExecuteReader()
isExist = reader.HasRows
End Using
End Using
con.Close()
End Using
Return isExist
End Function
Public Sub CreateDatabase(ByVal dataBase As String)
Dim conStr As String = "Data Source=192.168.0.1\SQL2005;Initial Catalog=master;uid=sa;pwd=pass@123;"
Dim con As SqlConnection = New SqlConnection(conStr)
Dim str As String = "CREATE DATABASE " & dataBase
Dim cmd As SqlCommand = New SqlCommand(str, con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
Screenshot