mysql - .NET - Importing class with connection to database -
i want import class class don't have write same code x times.
i have file connection database called connectdb.vb.
imports mysql.data.mysqlclient namespace connectdb1 public class connectdb dim connection new mysqlconnection("server=localhost; userid=root; password=root; database=something") public sub doconnection() try connection.open() catch ex exception msgbox("error") end try end sub end class end namespace
and want import connectdb.vb file1.vb
imports mysql.data.mysqlclient imports myapp.connectdb1 public class file1 dim connectdatabase new connectdb dim connection new mysqlconnection("server=localhost; userid=root; password=root; database=something") private sub file1_load(byval sender system.object, byval e system.eventargs) handles mybase.load 'doconnection() connectdatabase.doconnexion() end sub 'private sub doconnection() ' try ' connection.open() ' catch ex exception ' msgbox("error") ' end try 'end sub private sub addproduct() dim dbcomm mysqlcommand dim dbread mysqldatareader if txtboxquantity.text <> "" , txtboxprice.text <> "" , txtboxproduct.text <> "" dbcomm = new mysqlcommand("insert products (price, stock, name) values(@price, @stock, @name)", connection) dbcomm.parameters.addwithvalue("@price", txtboxprice.text()) dbcomm.parameters.addwithvalue("@stock", txtboxquantity.text()) dbcomm.parameters.addwithvalue("@name", txtboxproduct.text()) dbread = dbcomm.executereader() ' gives error dbread.close() end if end sub private sub add_click(byval sender system.object, byval e system.eventargs) handles agregarproducto.click addproduct() end sub end class
but when run code it's suposed save data in db gives me error:
invalidoperationexception unhandled. connection must valid , open.
connectdb.vb connects database since debugged , connects db, when want sql sentence in file1.vb gives error.
without trying import class code works, i'm trying improve code, can see commented code code used connect database.
try adding this
public sub new() connectdatabase = new connectdb() connection = new mysqlconnection("server=localhost; userid=root; password=root; database=something") end sub
Comments
Post a Comment