1

I've got a database client that will connect to a MySQL database. Much like the MySQL Workbench, I have a system in place to store connection credentials so that they can be called up later. I'm implementing this feature on my own in C#.

I have a WPF form in which these details would be entered. One of these controls takes in the IP address, which I'd like to store in a SQLite3 database file. Problem is, when I put the txtHostname.Text from the form and store it in the table (the particular column is a text-type column), it trips up on the "." between the digits in the IP address.

Let's say I'm using 127.0.0.1. The database will store up to 127, come across the ".0", and throw an error in the C#. This is a problem, of course.

Here's the code I'm using to create the .db file and create a table to hold information in:

    private void btnOK_Click(object sender, RoutedEventArgs e)
    {
        string fileName = txtConnectionName.Text + ".db";
        SQLiteConnection conn = CreateConnectionForSchemaCreation(fileName);

        using (SQLiteCommand cmd = new SQLiteCommand(conn))
        {
            cmd.CommandText = "CREATE TABLE Server_Details(ConnectionName TEXT PRIMARY KEY, Hostname TEXT NOT NULL, Username TEXT NOT NULL, Password TEXT NOT NULL, DefaultSchema TEXT NOT NULL)";
            cmd.ExecuteNonQuery();
            cmd.CommandText = String.Format("INSERT INTO Server_Details(ConnectionName,Hostname,Username,Password,DefaultSchema) VALUES({0},{1},{2},{3},{4})", txtConnectionName.Text, txtHostname.Text, txtUsername.Text, pwdPassword.Password, txtDefaultSchema.Text);
            cmd.ExecuteNonQuery();
        }
        conn.Close();
    }

I'm really more of a developer than a database analyst, so I'm a bit stumped here. I'd rather use the SQLite database to hold this information - it's far easier to work with than parsing a .txt file - but it would seem as if the data type to natively hold IP addresses isn't there in SQLite. I know I could possibly write a function to enable that, but it's been a while since I've done any SQL function work.

4

1 回答 1

0

如果您引用变量,它们将被视为文字值。

这给了我一个语法错误:

INSERT INTO Server_Details VALUES (Google, google.com, foo, bar, 127.0.0.1);

这执行得很好:

INSERT INTO Server_Details VALUES ('Google', 'google.com', 'foo', 'bar', '127.0.0.1');

不过,真的,现在是谈论准备好的语句SQL 注入的好时机。如果单独传递查询及其数据,则可以避免很多错误、安全问题和性能损失。

您没有提到您正在使用哪个特定的 DBI(有几个用于 C# 的 SQLite 库),但您可以在 Stack Overflow 上找到对准备好的语句的很好解释。您可以查看您的库文档中是否提及“准备好的语句”或“绑定变量”。

于 2013-07-25T17:34:33.487 回答