我有这个代码使用C#来操作SQL Server中的数据
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select * from Users where Username = @UserName and Password = @Password", myDatabaseConnection))
{
SqlCommand.CommandType = CommandType.Text;
SqlCommand.Parameters.AddWithValue("@UserName", TextBox1.Text);
SqlCommand.Parameters.AddWithValue("@Password", TextBox2.Text);
SqlDataReader DR1 = SqlCommand.ExecuteReader();
if (DR1.Read())
{
//somecodes
}
}
}
如何使用JDBC和MySQL作为数据库将其转换为Java?并且可以避免SQL注入。
试验:
try (Connection conn = DriverManager.getConnection(dbURL, username, password)) {
String sql = "Select * from Users where Username = @UserName and Password = @Password";
Statement statement = conn.createStatement();
//parameters?
ResultSet result = statement.executeQuery(sql);
while (result.next()){
//somecode
}
} catch (SQLException ex) {
ex.printStackTrace();
}
答案 0 :(得分:0)
JDBC使用?
个字符作为占位符,绑定变量通常会占用。您必须使用PreparedStatement
来使用?
占位符。然后你可以调用setXXX
方法(这里有基于1的索引!)来绑定变量然后执行。
String sql = "Select * from Users where Username = ? and Password = ?";
PreparedStatement pStatement = conn.prepareStatement(sql);
pStatement.setString(1, username);
pStatement.setString(2, password);
ResultSet rs = statement.executeQuery();