• 0

VB.NET connecting to MySQL [ODBC]


Question

4 answers to this question

Recommended Posts

  • 0

Last question...

I have the following code :

'Insert

MyCommand.CommandText = "INSERT INTO my_vb_net VALUES(30, computer.FullDomainName)"
Console.WriteLine("INSERT, Total rows affected:" & MyCommand.ExecuteNonQuery())

xml.WriteStartElement("Information")
xml.WriteElementString("Name", computer.FullDomainName)
xml.WriteElementString("Group", computer.RequestedTargetGroupName)
xml.WriteEndElement()

It will write the computer name to the xml file, but instead of inserting the computer name into the SQL db, it just puts computer.FullDomainName. I know with PHP you'd just put " . computer.FullDomainName . ", but unsure in .NET

Thanks :)

  • 0

OK. I finally got around to this. Sorry for the delay.

To use the .NET provider, download the setup and install it. In your project, add a reference to the MySql.Data.dll assembly. To use, well, here's an example of inserting, updating, getting, and deleting.

I'm using VB.NET 2005, so if you're not, sorry. You won't be able to use the Using statement. You'll have to use the Try Catch Finally to ensure your connection closes.

In the form load handler, i'm also showing 4 ways to get the hostname. The last one assumes you know at least the hostname or the IP, so it's a little redundant.

Imports System.Configuration
Imports MySql.Data.MySqlClient
Imports System.Text

<System.Runtime.InteropServices.ComVisible(False)> _
Public Class Form1
	Private conStr As String

	Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		' Getting the connection string from my app.config.
		' "server=localhost;user id=<userID>; password=<password>; database=test_db; pooling=false"
		Dim config As Configuration
		config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
		conStr = config.ConnectionStrings.ConnectionStrings("MySQL").ConnectionString

		' Use the My namespace
		Console.WriteLine(My.Computer.Name)
		' Use System.Environment
		Console.WriteLine(System.Environment.MachineName)
		' Use the Dns class
		Console.WriteLine(System.Net.Dns.GetHostName())
		' Use the Dns class to get more detailed info
		Dim host As System.Net.IPHostEntry
		host = System.Net.Dns.GetHostEntry("www.microsoft.comConsole.WriteLine(host.HostName)
	End Sub

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		' Create a record
		Using con As New MySqlConnection(conStr)
			con.Open()
			Dim cmd As New MySqlCommand()
			cmd.Connection = con
			cmd.CommandType = CommandType.StoredProcedure
			cmd.CommandText = "usp_insertupdate"
			Dim p As New MySqlParameter
			p.ParameterName = "_id"
			p.Value = 0
			cmd.Parameters.Add(p)
			p = New MySqlParameter("_fname", "John")
			cmd.Parameters.Add(p)
			p = New MySqlParameter("_lname", "Hamilton")
			cmd.Parameters.Add(p)
			p = New MySqlParameter("_age", 36)
			cmd.Parameters.Add(p)

			' Get back the id for the row
			Dim o_id As Object = cmd.ExecuteScalar()

			' Store the id in the button tag... cheesey, but hey, it's only an example
			Button1.Tag = o_id
		End Using
		Button1.Enabled = False
		Button3.Enabled = True
		Button2.Enabled = True
		Button4.Enabled = True
	End Sub

	Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
		' Get the record by id
		Using con As New MySqlConnection(conStr)
			con.Open()
			Dim cmd As New MySqlCommand("usp_getbyid", con)
			Dim p As New MySqlParameter("_id", Button1.Tag)
			cmd.CommandType = CommandType.StoredProcedure
			cmd.Parameters.Add(p)

			Dim r As MySqlDataReader
			r = cmd.ExecuteReader()

			' iterate throught the reader
			' bind to a ListBox... cheese, pure cheese...
			Dim sb As New StringBuilder(1024)
			While r.Read
				sb.AppendLine(String.Format("ID: {0}, First: {1}, Last: {2}, Age: {3}", _
				 r.GetInt32(0), r.GetString(1), r.GetString(2), r.GetInt32(3)))
			End While
			Dim s() As String = sb.ToString().Split(Environment.NewLine)
			ListBox1.DataSource = s

		End Using
	End Sub

	Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
		' Update the record.
		Using con As New MySqlConnection(conStr)
			con.Open()
			Dim cmd As New MySqlCommand("usp_insertupdate", con)
			cmd.CommandType = CommandType.StoredProcedure
			Dim p As New MySqlParameter("_id", Button1.Tag)
			cmd.Parameters.Add(p)
			p = New MySqlParameter("_fname", "Juan")
			cmd.Parameters.Add(p)
			p = New MySqlParameter("_lname", "DeMarco")
			cmd.Parameters.Add(p)
			p = New MySqlParameter("_age", 25)
			cmd.Parameters.Add(p)

			cmd.ExecuteNonQuery()
		End Using
	End Sub

	Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
		' Delete the record
		Using con As New MySqlConnection(conStr)
			con.Open()
			Dim cmd As New MySqlCommand("usp_delete", con)
			cmd.CommandType = CommandType.StoredProcedure
			Dim p As New MySqlParameter("_id", Button1.Tag)
			cmd.Parameters.Add(p)

			cmd.ExecuteNonQuery()

			Button1.Enabled = True
			Button3.Enabled = False
			Button2.Enabled = False
			Button4.Enabled = False

		End Using
	End Sub
End Class

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • They need to refactor their internal code to remove .NET Framework and third party libraries. Use .NET 10 or Rust. Stop bundling AI crap, it does not work.
    • Liberals have been , since the ‘60s, declaring that all you need is peace and love. At least until Trump ran for office. After that they have been letting out 50 years of repressed hatred. That’s all they really are anymore, angry and hateful. 
    • Zen Browser 1.14.6b by Razvan Serea Zen Browser is a privacy-focused, open-source web browser built on Mozilla Firefox, offering users a secure and customizable browsing experience. It emphasizes privacy by blocking trackers, ads, and ensuring your data isn't collected. With Zen Mods, users can enhance their browser experience with various customization options, including features like split views and vertical tabs. The browser is designed for efficiency, providing fast browsing speeds and a lightweight interface. Zen Browser prioritizes user control over the browsing experience, offering a minimal yet powerful alternative to traditional web browsers while keeping your online activity private. Zen Browser’s DRM limitation Zen Browser currently lacks support for DRM-protected content, meaning streaming services like Netflix and HBO Max are inaccessible. This is due to the absence of a Widevine license, which requires significant costs and is financially unfeasible for the developer. Additionally, applying for this license would require Zen to be part of a larger company, similar to Mozilla or Brave. Therefore, DRM-protected media won't be supported in Zen Browser for the foreseeable future. Zen Browser offers features that improve user experience, privacy, and customization: Privacy-Focused: Blocks trackers and minimizes data collection. Automatic Updates: Keeps the browser updated with security patches. Zen Mods: Customizable themes and layouts. Workspaces: Organize tabs into different workspaces. Compact Mode: Maximizes screen space by minimizing UI elements. Zen Glance: Quick website previews. Split Views: View multiple tabs in the same window. Sidebar: Access bookmarks and tools quickly. Vertical Tabs: Manage tabs vertically. Container Tabs: Separate browsing sessions. Fast Profile Switcher: Switch between profiles easily. Tab Folders: Organize tabs into folders. Customizable UI: Personalize browser interface. Security Features: Inherits Firefox’s robust security. Fast Performance: Lightweight and optimized for speed. Zen Mods Customization: Deep customization with mods. Quick Access: Easy access to favorite websites. Open Source: Built on Mozilla Firefox with community collaboration. Community-Driven: Active development and feedback from users. GitHub Repository: Contribute and review the source code. Zen Browser 1.14.6b changelog: Security Various security fixes New Features Updated to Firefox 141.0 Improved accent color detection, making elements such as toasts more vibrant. Added a better custom color picker (experimental UI, might change) Improved and optimized glance animations and UI WebGPU is now enabled by default on windows Added a more native feel to windows 11 window buttons Fixes picture caching and scroll optimization issues a bug where adding or removing colors in the color picker would make the UI white On Linux, Zen uses less memory and no longer requires a forced restart after an update has been applied by a package manager. Fixed 'copy calculation' in the urlbar not working Download: Zen Browser | 82.3 MB (Open Source) Download: Zen Browser ARM64 | Other Operating Systems View: Zen Browser Home Page | Screenshots 1 | 2 | Reddit Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • You reap as you sow - he enabled hate, so he can receive a level of it.
    • It is informal speech, it just means to get rid of whatever is preinstalled on the disk. The steps you mentioned in one of your posts are enough, there is no need to overwrite the disk with zeros, random patterns, etc., deleting the existing partitions and installing Windows anew suffices. Even if you wanted to recover data from whatever was there previously, I wager you wouldn't be able to because of how SSDs work (if you want to know more about it, look for TRIM in that context). It is likely the drive doesn't have just 1 partition like you said though, 2-3 would be standard (EFI/boot, Windows, Recovery, maybe even a small reserved one), but you can remove them all during installation: - Press Shift+F10 once Setup appears when booting from the Windows installation media, a command line window should appear. - Run "diskpart" (type it, press Enter), list the disks attached to the machine and select the internal one, the one you want to clean. - Once selected, type "clean" followed by Enter, there'd be nothing on that drive afterwards. Type "exit" to quit DiskPart, and you can close that CMD and continue with Windows installation as usual. It should be something like this: Just beware of which disk you select before cleaning, you can use "detail disk" after selecting one to get some details about it.   Yes, if you install Windows from scratch from known-good installation media you can rest easy about that. Firmware rootkits or similar would still be there if they were, but I don't think you should worry.   It depends on who you ask, I'd say most people find it to be enough; a full scan after installing Windows shouldn't produce any positive result. Like Nik said, absolute certainty is not something that can be attained, but one can be confident enough.
  • Recent Achievements

    • Dedicated
      Snake Doc earned a badge
      Dedicated
    • One Month Later
      Philsl earned a badge
      One Month Later
    • One Year In
      armandointerior640 earned a badge
      One Year In
    • One Month Later
      armandointerior640 earned a badge
      One Month Later
    • Week One Done
      Itbob513626 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      613
    2. 2
      ATLien_0
      236
    3. 3
      Xenon
      156
    4. 4
      +FloatingFatMan
      123
    5. 5
      Michael Scrip
      113
  • Tell a friend

    Love Neowin? Tell a friend!