Sorry for posting so many nubbin questions on ASP.net, I’m getting the hang of it slowly.
I execute queries on my pages as such (working):
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
// When the registration form is submitted
protected void regSubmit(object sender, EventArgs e)
{
// No erros so far
Boolean anyError = false;
string errorMessages = "";
// Take all form values
string username = txtUsername.Text;
string password1 = txtPassword1.Text;
string password2 = txtPassword2.Text;
string emailAdd = txtEmail.Text;
// Verify that username is unique
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE username = '" + username + "'", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
int result = int.Parse(rdr[0].ToString()); //read a value
}
statusLabel.Text = username;
}
</script>
My question is, is this the best practise, do I have to have a ‘using’ block and that inner structure for every query I run, or is there a simpler way of doing it? Also, do I need to close anything off or does the garbage man take care of it?
In Classic ASP I would just have a
adoCon.execute("DELETE FROM TABLE")
or a
rsCommon.open("SELECT * FROM TABLE"), adoCon
do until rsCommon.EOF
rscommon.movenext
loop
rsCommon.close
Tallyho! Thank you for any help!
Which seems a lot simpler and intuitive to me.
Tom,
You’ve got a few bits of bad stuff going on here (sorry to be so blunt). I’d look at the following:
SQL injection attacks
BLL layers (or at the very least,
isolate it for reuse into classes where possible)
Also,
Boolean anyError = false;never get’s used but i’m assuming that’s for later use.On the bright side, the idea of the using block is good, so keep that up. You can find references online to help with decoupling your logic and parameterized queries.
go with the flow
jim