How do I make the user choose the name of the database? - vb.net

in my project i need some changes in my code to give the user choose the name of sql database !
and this is My original code:
Dim DssD As String
DssD = TextBox1.Text
Zsql = "CREATE DATABASE my_db ON PRIMARY" +
"(Name=my_db, filename = 'D:\DB\SQL\my_db.mdf')log on" +
"(name=my_db_log, filename='D:\DB\SQL\my_db_log.ldf')"
Zcmd = New SqlCommand(Zsql, Zsqlcon)
Try
Zsqlcon.Open()
Zcmd.ExecuteNonQuery()
Zsqlcon.Close()
MsgBox("Done", MsgBoxStyle.Information, " ZerAllail")
Catch
MsgBox("Somthing wrong", MsgBoxStyle.Critical, " ZerAllail")
End Try
its working good but its not create the log fail !

You can use a interpolated string (preceded with $) if you are using Visual Studio 2015 or later. You can embed variables directly into the string enclosed in braces. Otherwise see String.Format.
I added a Using...End Using block to your code because connections and commands need to closed and disposed. They use unmanaged resources and need to release them in their .Dispose methods. A Using block will do this for you even if there is an error.
Private Sub CreateDatabase()
Dim DssD = TextBox1.Text 'I would expect you would validata this input
Dim Zsql = $"CREATE DATABASE {DssD} ON PRIMARY (Name=my_db, filename = 'D:\DB\SQL\{DssD}.mdf')log on
(name={DssD}_log, filename='D:\DB\SQL\{DssD}_log.ldf')"
Try
Using Zsqlcon As New SqlConnection("Your connection string"),
Zcmd = New SqlCommand(Zsql, Zsqlcon)
Zsqlcon.Open()
Zcmd.ExecuteNonQuery()
End Using
MsgBox("Done", MsgBoxStyle.Information, " ZerAllail")
Catch
MsgBox("Somthing wrong", MsgBoxStyle.Critical, " ZerAllail")
End Try
End Sub

Related

the connectionstring property has not been initialized in vb.net

Everytime I click the button where the sub procedure execute, I'm getting the error "the connection string property has not been initialized"
Here is my code
Sub CheckExistingExp()
Dim aexpcheckifexisting As New DataSet
Dim bexpcheckifexisting As New OleDb.OleDbDataAdapter
Dim sqlcheck As String
Dim duplicateexp As Integer
sqlcheck = "select count(exp_doc) vcount from csap_exph where exp_doc = '" & RQuote(txtExpDoc.Text) & "' and status = 'A'"
bexpcheckifexisting = New OleDb.OleDbDataAdapter(sqlcheck, con)
bexpcheckifexisting.Fill(aexpcheckifexisting, "checkduplicateexp")
duplicateexp = aexpcheckifexisting.Tables("checkduplicateexp").Rows(0).Item("vcount")
If duplicateexp > 0 Then
If MsgBox("Expense Doc is already existing, are you sure you want to tag it as posted?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Approve_Expense()
Else
con.Close()
End If
End If
End Sub
What should I do to solve this?
Thanks.
Let alone the connection string which is missing, where did you open con for you to close it? [con.open()] and if your user hits MsgBoxResult.Yes your connection would stay open cause con.Close() is only called if duplicateexp <= 0.
dispose your con at the end of your code or use using which closes it automatically and use a try-catch to catch any errors.
have your connection string somewhere in app.config or make it public in a class or module or whatever you prefer and make your string = that value and open your connection at the beginning of the sub.

System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed

I am having a problem with a customer service module which is in a different solution. the problem I think is in my method of calling or getting a connection
here is my class called DBConnForAccess
Imports System.Data.OleDb
Imports System.Data.Odbc
Public Class DBConnForAccess
Dim Conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim Trans As OleDbTransaction
Public Function DBConnect(ByVal filePath As String, pass As String)
Try
' open Database
'Conn = New SqlConnection("Data Source=" + ServerName + "\" + DBName + ";User ID=" + DBUsername + ";Password=" + DBPassword + ";Initial Catalog= '" + TB + "'")
Conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Jet OLEDB:Database Password=" + pass + ";")
' "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;"
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
' create transaction
Trans = Conn.BeginTransaction
Return "Ok"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Sub ExecuteSQL(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
'execute the sql
CMD.ExecuteNonQuery()
End Sub
Public Sub commit()
Me.Trans.Commit()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub rollback()
Me.Trans.Rollback()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub CloseDB()
Me.Conn.Close()
Me.Conn.Dispose()
Me.Trans.Dispose()
End Sub
Public Function ReadData(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
Dim R = CMD.ExecuteReader()
'Do While R.Read
'Loop
Return R
End Function
End Class
Here is the Sub I use to fetch Data:
Dim connection As String = txt_util.readFromTextFile("ConnStr_2.txt", 0) + "Billing.mdb"
'connection string is in a text file with text at line 0 as "C:\BILLSERV\"
Private Sub searchAccnt(ByVal SIN As String)
'clear other fields
Clear("Acct")
Try
AccntDetail.DBConnect("ConcessionairesAccnt")
'Dim RS = AccntDetail.ReadData("Select * From AllAccounts Where SIN=#0", txtSIN.Text.Trim)
Dim RS = AccntDetail.ReadData("Select * From viewCSFAccnt Where SIN=#0", SIN)
RS.Read()
If RS.Hasrows = 0 Then
MsgBox("Accounts not found. Check the SIN you Enter.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records not found.")
'txtAppNo.Focus()
Exit Sub
Else
'MsgBox("Accounts correct.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records found.")
txtZoneNo.Text = RS.Item("Zone").ToString
txtSeq.Text = RS.Item("SeqNo").ToString
txtAccntName.Text = RS.Item("AccountName").ToString
txtAccntAddress.Text = RS.Item("HouseNo").ToString + " " + RS.Item("BLDGName").ToString + " " + RS.Item("Street").ToString + _
" " + RS.Item("BRGY").ToString
txtMeterNo.Text = RS.Item("MeterNo").ToString
txtAccntStatus.Text = varA.AccntStatus(RS.Item("Status").ToString)
'Dim con = AccessAccnt.DBConnect(connection, "")
'If con <> "Ok" Then
' MsgBox("Cannot establish a Connection to the server.", MsgBoxStyle.Critical, "Connection Lost...")
'End If
Dim ZoneNo = "Z" + GetChar(txtZoneNo.Text, 1) + GetChar(txtZoneNo.Text, 2) + "B" + GetChar(txtZoneNo.Text, 3) + GetChar(txtZoneNo.Text, 4)
AccessAccnt.DBConnect(connection, "")
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
Acc.Read()
txtLastReading.Text = Acc.Item("LastReading").ToString
Acc.close()
AccessAccnt.CloseDB()
End If
RS.Dispose()
AccntDetail.CloseDB()
dbCounter.DBConnect("ConcessionairesAccnt")
Dim result = dbCounter.ReadData("Select Top 1 CSFNo From CSFMaster WHERE (CSFNo LIKE '%" & ctrDate() & "%') order by CSFNo Desc")
result.read()
If result.hasrows = 0 Then
txtTrackingNo.Text = ctrDate() & "-" & "000001"
Else
txtTrackingNo.Text = counter.CtrLastItemWithChar("ConcessionairesAccnt", "CSFNo", "CSFMaster", "WHERE (CSFNo LIKE '%" & ctrDate() & "%') ORDER BY CSFNo DESC", 5)
End If
dbCounter.CloseDB()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The Error is thrown here:
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
It Says:
System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed.
The Other Parts of the Sub Works fine, The part where I fetch Data on my MSSQL Server database. The Problem lies in the Access data-Fetching Code.
I tried Using the code on another project (just the code where i fetch access data) I worked on other solutions. But I copy and paste my code on any form in this solution I keeps giving the Error.
I thought Maybe I closed the connection somewhere but this is the only instance I used this code in this entire project. (Just to get the last reading record.)
The Database is in the correct place (C:\BILLSERV)
I've Tried searching it here on SE but all I can see where suggestions about maybe forgetting to open the connection. I used this code before and this code works on my other solutions. I just cant seem to have it work here on this particular project. I wonder Why..
I tried running another project using this code and it works fine.
Is there a bug about Access connection on VB.net 2012, I have been using this code (DBConnForAccess Class) for about a year now and this is the first time I have encountered this error. btw I use Access 2003 because this database used to be for an old system created in VB6.
Lastly could this be because the solution came from another computer using a VB.Net Program same as mine. Because We work as a team here. Hope someone with a better knowledge on these systems could help. Thanks in advance.
EDIT
If a connection has been made, there should be a .ldb file in access which should appear. (I tested this on another project and an ldb file appear once a connection has been made, as we all know ldb file contains the data of the user using the db file.) I tried to re-run the system and while I'm using the system no ldb file was created.
Also,I thought Maybe I closed the connection somewhere but this is the only instance I opened a connection in access and which I used the code in this entire project. (Just to get the last reading record.)
So this is NOT a duplicate of “There is already an open DataReader…” Reuse or Dispose DB Connections? Just for clarifications
After a week of debugging and reading articles in the web.
We have found the culprit of the Error.
Seems that the Target CPU Option in Advance compiler Settings was change to AnuCPU.
We noticed this after we checked the other application projects we used.
Changing it Back to x86 solves the connection problem.
I wonder why this affected the connection to the access.
All is working fine now. thank you Plutonix and Steve for all your suggestions we'll be having a change in our codes.

i am trying to use an input from the user as part of a connection string to a SQL database

my connection string is saved in a string variable names str
what i am trying to do is use an input from the user as part of the string
the parts i want to take from the user are the ID and PASS
i am simply trying to check the connection statues with the ID and the PASS as inputs from the user.
Dim str As String = "Data Source=DESKTOP;uid=ID;pwd=PASS;database=DB"
Dim conn As New SqlConnection(str)
Private Sub btnconnect_Click(sender As Object, e As EventArgs) Handles btnconnect.Click
PW = txtadminpass.Text
Try
conn.Open()
conn.Close()
MsgBox("GOOD")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
i haven't had much like while using the + and & for the strings.
any help would be appreciated.
The SqlConnectionStringBuilder is an appropriate class to use in this case. You can add parts of the connection string to it via properties, so there is no chance of making mistakes:
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim csb As New SqlConnectionStringBuilder
csb.DataSource = "DESKTOP"
csb.InitialCatalog = "DB"
csb.UserID = "z"
csb.Password = "x"
' output "Data Source=DESKTOP;Initial Catalog=DB;User ID=z;Password=x" '
Console.WriteLine(csb.ToString())
Console.ReadLine()
End Sub
End Module
So, you need to check if the user is allowed to log into the database or not. The way you have followed looks good, you define the connection string based on the given ID and password, and you try to establish a connection, if it fails, the user can't log in, else he can do that.
However, the way you defined the string is wrong, you must use concatenation to preserve the ID and password values, try this,
Dim str As String = "Data Source=DESKTOP; uid=" & ID & "; pwd=" & PASS & ";database=DB"
Another way, which makes it easy to read:
Const CONN_STRING As String = "Data Source=DESKTOP;uid={0};pwd={1};database=DB"
Dim connString As String = String.Format(CONN_STRING, txtUserID.Text.Trim, txtPassword.Text)

an error after log in: "There is already an open DataReader associated with this connection which must be closed first?"

I retrieve it in my mainform:
Try
rs.Connection = con
cmd = "select * from cdcol.currency_rate"
rs.CommandText = cmd
res = rs.ExecuteReader
While res.Read
Dim currency = res.GetString("currency")
ComboBox2.Items.Add(currency)
End While
res.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
and this in my tabcontrol
Try
rs.Connection = con
cmd = "select * from cdcol.currency_rate where currency='" & ComboBox2.Text & "'"
rs.CommandText = cmd
res = rs.ExecuteReader
While res.Read
If sell.Checked = True Then
buy.Text = res.GetDouble("buy_rate")
coderate.Text = res.GetString("code")
End If
If buy.Checked = True Then
sell.Text = res.GetDouble("sell_rate")
coderate.Text = ("PHP")
End If
End While
res.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
when i log in there was an error,
what's wrong with my codes ?
please help me ..
A few things could be going on, hard to tell without all the code but I'll give you some ideas. I'm assuming this is a WinForms app (also assuming this is SQL Server)?
If you've verified that all your DataReader's are being closed properly then it is possible that you have two DataReaders actually trying to read at the same time if they're using a shared connection in your program (you say you're using a tab control and executing a query, if you have one reader running somewhere and then you click on a tab you could run into that scenario). If that is your desired behavior you can allow multiple recordsets by adding the multiple active result sets flag to your connection string:
https://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.110).aspx
Something like this:
Dim connectionString As String = "Data Source=MSSQL1;" & _
"Initial Catalog=AdventureWorks;Integrated Security=SSPI;" & _
"MultipleActiveResultSets=True"
The MSDN article gives you much more info about it. In your scenario this will probably work. MSDN offers this though (which is your other option, use a connection per method you need it and dispose of it when you're done):
"MARS is not designed to remove all requirements for multiple
connections in an application. If an application needs true parallel
execution of commands against a server, multiple connections should be
used."

How to format an IBM data library into a command prompt window so that it's readable (to a human)?

Ok, here's my Code:
Imports IBM.Data.DB2.iSeries
Module ConsoleData1
Sub Main()
'program identifier (to verify that you're using the right module)
Console.WriteLine("ConsoleData1.vb")
'create the connection object to the IBM i
Using cn As New iDB2Connection("DataSource=xxxxxxxxxxxxx")
Try
cn.Open()
Catch ex As iDB2Exception
Console.WriteLine("An error occurred on cn.Open()")
Exit Sub
End Try
'create a command object, initialize to valid SQL statement
Using cmd As New iDB2Command("select * from testlib.finishk", cn)
'create a command object, initialize to valid SQL statement
Console.Write("Enter the Color Code!==>")
Dim baldue = Console.ReadLine()
Dim sql As String = "Select * from testlib.finishk where FINCOD >=" & FINCOD
Using cmdx As New iDB2Command(sql, cn)
End Using
'create a data reader object, fill by executing the command
Try
Using dr As iDB2DataReader = cmd.ExecuteReader
'display data in a table
Console.Write("FINCOD" & vbTab)
Console.Write("FINDES" & vbTab)
While dr.Read()
Console.Write("{0}{1}", dr("FINCOD"), vbTab)
Console.Write("{0}{1}", dr("FINDES"), vbTab)
End While
End Using
Catch ex As iDB2Exception
Console.WriteLine("An error occurred on cmd.ExecuteReader()")
Exit Sub
End Try
End Using
End Using
Console.WriteLine("Press ENTER to end")
Console.ReadLine()
End Sub
Sub HandleError(ByVal errorOccurred As String, ByVal ex As iDB2Exception)
Console.WriteLine(errorOccurred)
Console.WriteLine("Source: {0}", ex.Source)
Console.WriteLine("SQLState: {0}", ex.SqlState)
Console.WriteLine("Message: {0}", ex.Message)
Console.WriteLine("MessageCode: {0}", ex.MessageCode)
Console.WriteLine("MessageDetails: {0}", ex.MessageDetails)
Console.ReadLine()
End Sub
Private Function Screen() As Object
Throw New NotImplementedException
End Function
End Module
Now, how would I make it so that I can resize the cmd window to be larger and still retain the integrity of the table structure? If I resize the cmd window, it ends up looking like someone just threw the values into a window in random placement.
Thanks.
You need two things: a line break between each record and length information in your format string (to shoot for fixed width columns).
'You can play the -30 numbers here to get different spacing, based on the nature of your data
Dim recordFormat As String = "{0,-30} {1,-30}"
Console.WriteLine(recordFormat, "FINCOD","FINDES")
While dr.Read()
Console.WriteLine(recordFormat, dr("FINCOD"), dr("FINDES"))
End While
Finally, I'm not familiar with DB2, but please tell me there's a better way than string concatenation to add the user's FINDCOD value to the sql statement? What you're doing is horribly unforgivably insecure. What if I put the text 0;DROP TABLE testlib.finishk;-- into your system instead of a FINDCOD? Any sane code would use parameterized queries for this.