如何从C#转换为Java JDBC

问题描述 投票:0回答:1

我有使用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())
        {
            //some code
        }
    }
}

我将如何使用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()) {
        //some code
    }        
} catch (SQLException ex) {
    ex.printStackTrace();
}
c# java mysql jdbc
1个回答
1
投票

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();
© www.soinside.com 2019 - 2024. All rights reserved.