c# - Insert null value in database -
i have database in mysql workbench fields (name, lastname, age, address, etc..) , windows desktop application (a form) in visual studio c# can insert, search , update. when insert data form , leave fields empty, saved in database blank , want them saved null. there way make happen?
here , insert button code:
conn = openconnection.getconn(); mysqlcommand cmd = new mysqlcommand("insert table_name (name,lastname,address, etc...) values (' " + name_textbox.text + " ',' " + lastname_textbox.text + " ' etc... );", conn); cmd.commandtype = commandtype.text; cmd.executenonquery(); conn.close(); thanks lot, works fine have problem words spaces, like: (father name , mother name , etc). when insert value @ name fine when insert value @ father name or mother name null. think because of space between words.
mysqlcommand cmd = new mysqlcommand("insert table_name (name,`father name`,`mother name`, etc... values (@name,@`father name`,@`mother name`,etc...);", conn); cmd.parameters.addwithvalue("@name", name_textbox.text.nullstring()); cmd.parameters.addwithvalue("@`father name`", father_name_textbox.text.nullstring()); cmd.parameters.addwithvalue("@`mother name`", mother_name_textbox.text.nullstring()); cmd.executenonquery();
one way interpretation on own:
string.isnullorempty(name_textbox.text) ? null : string.format("'{0}'", name_textbox.text); however, want give option:
using (mysqlconnection conn = openconnection.getconn()) { using (mysqlcommand cmd = new mysqlcommand("insert table_name (name,lastname,address) values (@name,@lastname,@address);", conn); { cmd.parameters.addwithvalue("@name", name_textbox.text.nullstring()); cmd.parameters.addwithvalue("@lastname", lastname_textbox.text.nullstring()); cmd.parameters.addwithvalue("@address", address_textbox.text.nullstring()); cmd.executenonquery(); } } namespace system { public static class stringextensions { public static string nullstring(this string s) { return string.isnullorempty(s) ? null : s; } } } with solution you'll disposing connection , command objects, you'll able streamline string null process and leverage prepared queries make process simpler and safer because it's not open sql injection.
note: static class see should placed in own .cs file.
Comments
Post a Comment