Visual Basic connect database with ODBC setting with register - mysql

I have the code written to connect to the ODBC registry.
The database name is written to the combobox.
I need to transfer my ip address and password from ODBC.ini to the connect string after selecting the database from the combobox.
This is a connection to MYSQL.
Thank you
Private Sub DsnLookup()
Dim dsnNames As New List(Of String)
Dim reg As Microsoft.Win32.RegistryKey = Registry.CurrentUser.OpenSubKey("Software")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC.INI")
If reg IsNot Nothing Then
For Each dsn As String In reg.GetSubKeyNames
dsnNames.Add(dsn)
Next
End If
End If
End If
For Each Name As String In dsnNames
ComboBox1.Items.Add(Name)
Next Name
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DsnLookup()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connString As String = "Database='combobox data;Data Source='ip adres odbc;" _
& "User Id=root;Password=' odbc PWD"

You can get the Server Name (or IP) and Database name from the ODBC.INI but it doesn't store the password. Either include a master password in your connectionstring (securely of course) or look into other authentication options.
This is how to get the Database and Server info from the registry. Keeping your code the same, but replacing the Button1.Click event and adding an additional function:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex >= 0 Then 'Make sure something from dropdown selected
Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValue(ComboBox1.SelectedItem, "Database"), GetODBCValue(ComboBox1.SelectedItem, "Server"))
End If
End Sub
Private Function GetODBCValue(ByVal ODBCName As String, ByVal ValueName As String) As String
Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
reg = reg.OpenSubKey("ODBC")
reg = reg.OpenSubKey("ODBC.INI")
reg = reg.OpenSubKey(ODBCName)
Return reg.GetValue(ValueName)
End Function

thank you for the answer
I tried to edit it
Private Function GetODBCValu(ByVal ODBCName As String, ByVal ValueName As String) As String
Dim dsnNames As New List(Of String)
Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
reg = reg.OpenSubKey("ODBC")
reg = reg.OpenSubKey("ODBC.INI")
reg = reg.OpenSubKey(ODBCName)
Return reg.GetValue(ValueName)
For Each dsn As String In reg.GetSubKeyNames
dsnNames.Add(dsn)
Next
For Each Name As String In dsnNames
ComboBox1.Items.Add(Name)
Next Name
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValu(ComboBox1.SelectedItem, "Database"), GetODBCValu(ComboBox1.SelectedItem, "Server"))
Dim conn As New MySqlConnection(connString)
Dim cmd As New MySqlCommand()
Try
Call conecDB()
dt = New DataTable 's_table
Dim con As New SqlConnection
DateTimePicker1.CustomFormat = "yyyy-MM-dd"
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker2.CustomFormat = "yyyy-MM-dd"
DateTimePicker2.Format = DateTimePickerFormat.Custom
conn.Open()
cmd.Connection = conn
da = New MySql.Data.MySqlClient.MySqlDataAdapter("select --- ", connDB)
comBuilderDB = New MySql.Data.MySqlClient.MySqlCommandBuilder(da)
da.Fill(dt)
dbvypis.DataSource = dt
conn.Close()
MessageBox.Show("COMPLET")
Catch ex As MySqlException
Console.WriteLine("Error: " & ex.ToString())
End Try
Try
'declaring variable as integer to store the value of the total rows in the datagridview
Dim max As Integer = dbvypis.Rows.Count - 1
Dim total As String = "TOTAL ----->"
Dim TOTALCOST As Integer = 0
'getting the values of a specific rows
For Each row As DataGridViewRow In dbvypis.Rows
'formula for adding the values in the rows
TOTALCOST += row.Cells(1).Value
Next
dbvypis.Rows(max).Cells(1).Value += TOTALCOST
dbvypis.Rows(max).Cells(0).Value = total
Catch ex As Exception
MsgBox(ex.Message)
End Try
It occurred to me that if I select a database in the comboboxu so it gets into ODBC and connString to the command adds the server and database name
Then it writes to me in the result Index is out of range, Index must be non-negative and must be smaller than the collection size. Parameter name: index

Related

Uploading Datagridview data to MySQL DB

i created a simple mass upload of data from CSV to datagridview and save all datagridview rows into my MySQL table, the code works perfectly but when i check my database it insert a null values to my table heres my code.
This is my Button for Adding all values from my Datagridview
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As MySqlCommand
connection.Open()
Dim i As Integer
For i = 0 To DataGridView1.Rows.Count - 2
Dim row As DataGridViewRow = DataGridView1.Rows(i)
cmd = New MySqlCommand("INSERT INTO tbl_handling(tbl_docnumber,tbl_bpref,tbl_cname) values (#docnumber,#bref,#cname)", connection)
cmd.Parameters.Add("#docnumber", MySqlDbType.Int64).Value = DataGridView1.Rows(i).Cells(0).Value.ToString
cmd.Parameters.Add("#bref", MySqlDbType.VarChar).Value = DataGridView1.Rows(i).Cells(1).Value.ToString
cmd.Parameters.Add("#cname", MySqlDbType.VarChar).Value = DataGridView1.Rows(i).Cells(2).Value.ToString
cmd.ExecuteNonQuery()
Next
connection.Close()
connection.Dispose()
MessageBox.Show("Data All Uploaded")
End Sub
This is my code on inserting CSV file to my Datagrid view
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectData.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "D:\TestFile"
OpenFileDialog1.Filter = "CSV files(*.csv)|*.csv"
OpenFileDialog1.RestoreDirectory = True
Dim colespected As Integer = 5
Dim sline As String = ""
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
Dim thereader As New StreamReader(fName, Encoding.Default)
Do
sline = thereader.ReadLine
If sline Is Nothing Then Exit Do
Dim words() As String = sline.Split(",")
DataGridView1.Rows.Add("")
For ix As Integer = 0 To 2
DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(ix).Value = words(ix)
Next
Loop
thereader.Close()
End If
End Sub
I am assuming that your data is displaying successfully in the grid. So I am only addressing the Button event.
Both commands and connections need to be closed and disposed. Using...End Using blocks do this for you. (BTW Stream objects should be in Using blocks also.) Database objects should be local to the method where they are used. If you .Dispose a connection how do you expect to .Open it later? The command and parameters collection are only created once outside the loop. Just the .Value changes inside the loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using connection As New MySqlConnection(ConStr),
cmd As New MySqlCommand("INSERT INTO tbl_handling(tbl_docnumber,tbl_bpref,tbl_cname) values (#docnumber,#bref,#cname)", connection)
cmd.Parameters.Add("#docnumber", MySqlDbType.Int64)
cmd.Parameters.Add("#bref", MySqlDbType.VarChar)
cmd.Parameters.Add("#cname", MySqlDbType.VarChar)
connection.Open()
For i = 0 To DataGridView1.Rows.Count - 2
cmd.Parameters("#docnumber").Value = CLng(DataGridView1.Rows(i).Cells(0).Value)
cmd.Parameters("#bref").Value = DataGridView1.Rows(i).Cells(1).Value.ToString
cmd.Parameters("#cname").Value = DataGridView1.Rows(i).Cells(2).Value.ToString
cmd.ExecuteNonQuery()
Next
End Using
MessageBox.Show("Data All Uploaded")
End Sub
I am a bit worried that tbl_docnumber is an auto-number (identity) primary key in the database. If this is so, then this field should be omitted from the Insert.
This operation would be easier if you filled a DataTable instead of a DataGridView. You could then use a DataAdapter to update the database.

VB.Net from table(time data type) to label

I have a problem regarding producing report but before that I need to run a code in order for me to create multiple conditions for the next report.
I have here a screenshot of my tbldtr. What I want is the value of am_time_in which has the data type of time will be transferred into a label/textbox/variable. I am using Visual Basic with MySQL.
Here is my code
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
checktime()
End Sub
Private Sub checktime()
Dim cn As New MySqlConnection(CnPath)
Dim Sql As String = "SELECT `tbldtr`.`am_time_in` FROM `tbldtr` WHERE `tbldtr`.`id` = '11' AND `tbldtr`.`dtrdate` = '2017-10-16'"
Dim daCmd5 As New MySqlCommand(Sql, cn)
cn.Open()
Dim datinfo As MySqlDataReader = daCmd5.ExecuteReader()
While datinfo.Read()
If IsDBNull(datinfo(0)) = True Then
lblamtimein.Text = ""
Else
lblamtimein.Text = datinfo(0)
End If
End While
cn.Close()
End Sub
End Class
Error here:
The error is occurring on this line -
lblamtimein.Text = datinfo(0)
A timespan needs to be explicitly converted to a string like this -
lblamtimein.Text = datinfo(0).ToString

Adding a record in Datagridview Row in Vb.net

Hello I have Datagridview in my vb.net form and i want to display the data from the MySQL table to the Datagridview (Dgv) of Vb.net but the problem is when i update or delete an record in Dgv the current record that i fetch is adding more display of the current record. I write this code like this because I'm going to add more function on it, I know i can do this using MySqlDataAdapter and DataSet then fill the datagridview of this code but i use this to add more function, for now how can i update/delete an record without adding more rows that i currently fetch. or doubling the row's
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
Dim row() As String
row = new String() {empId, empName, empAddress}
DataGridView1.Rows.Add(row)
End While
reader.close()
cmd.close()
I know the problem is in Rows.Add
Added:
Currently the function of this is to display the data and when event or button was click this Sub will be called again. with out adding more display.
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
'before adding new row in datagridview add this code
DataGridView1.Rows.clear();
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
so that it will remove the old value of the row and then add the new value in the database
This should do what you want. You can easily select from sql server to datagridview, change data, and pass change from datagridview to sql server.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source='your_server';Initial Catalog='your_database';Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

MySQL query (sum) not working in VB

I want to add the ages of all the employees in MySQL database column(using sum query) and then want to display its result(the value)on the click of a button in VB in a textbox.I have given a try but its not working.I am not able to figure this out.Please help....Image
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim Mysqlconn As New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=andy1234;database=data"
Try
Mysqlconn.Open()
command.Connection = Mysqlconn
command.CommandText = "select sum(age) from data.etable"
Dim sqlresult As Object
sqlresult = command.ExecuteScalar
Dim str As String
str = sqlresult
TextBox5.Text = str
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
a demo on standard port 3306 for Mysql
Schema
create table etable
( eid int auto_increment primary key,
age int not null
);
insert etable(age) values (1),(2),(3);
VB Code
Imports MySql.Data.MySqlClient
Public Class Form1
Dim conn As New MySqlConnection
Public Sub connect()
' Perform a connection test, and save ConnectionString
' in Module-level variable "conn"
Dim dbname As String = "dbname"
Dim hostname As String = "hostname"
Dim user As String = "dbuser"
Dim password As String = "password"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}", hostname, user, password, dbname)
Try
conn.Open()
MsgBox("Connection Test Successful")
' and ConnectionString set for subsequent queries
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close() ' close connection for now
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
connect()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim iAgeSum As Integer
Try
conn.Open()
Catch ex As Exception
End Try
Dim cmd As New MySqlCommand(String.Format("select sum(age) as ageSum from etable"), conn)
Dim result = cmd.ExecuteScalar()
If result Is Nothing Then
TextBox1.Text = "junk"
Else
iAgeSum = Convert.ToInt32(result.ToString()) ' for the purpose of showing conversion
TextBox1.Text = iAgeSum
End If
conn.Close()
End Sub
End Class
Screenshot

Unsure of how to handle a NullReferenceException

When my form for creating a group of students loads up, I receive a NullReferenceException for seemingly no reason. This is the code that handles the form loading:
Private Sub AddGroupForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To Form1.lstStudents.Items.Count - 1
lstStudentList.Items.Add(Form1.lstStudents.Items.Item(i))
Next
tempStudentList.AddRange(Form1.mainStudentList)
btnAllOut.Enabled = False
btnOneOut.Enabled = False
End Sub
The mainStudentList referred to is a list that is populated upon loading by using MySQL:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim conn As New MySqlConnection("server=localhost;user=root;database=new_project;port=3306;password=********;")
conn.Open()
Dim command As New MySqlCommand("SELECT * FROM students WHERE deleted=0 ORDER BY lastName;", conn)
Dim dataSet As New DataSet()
Dim dataAdapter As New MySqlDataAdapter()
dataAdapter.SelectCommand = command
dataAdapter.Fill(dataSet, "students")
Dim dataTable As DataTable = dataSet.Tables("students")
For Each row As DataRow In dataTable.Rows
Dim newStudent As New Student
newStudent.intIDNum = row.Item("passCode")
newStudent.strFirstName = row.Item("firstName")
newStudent.strLastName = row.Item("lastName")
newStudent.chrGender = row.Item("gender")
newStudent.dateDOB = row.Item("dateOfBirth")
newStudent.intAge = CInt(Today.Year - newStudent.dateDOB.Year)
newStudent.intYearGroup = row.Item("yearGroup")
newStudent.intSkillLevel = SByte.Parse(row.Item("skillLevel"))
mainStudentList.Add(newStudent)
lstStudents.Items.Add(newStudent.nameConcat(newStudent.strFirstName, newStudent.strLastName))
Next
conn.Close()
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try
End Sub
The specific exception occurs when the tempStudentList attempts to load the values in the mainStudentList. Specifically, it states that "Object reference not set to instance of an Object".
Make sure mainStudentList has been initialized first.
c#
List<Student> mainStudentList = new List<Student>();
VB.Net
Dim mainStudentList As New List(Of Student)()