我目前正在尝试用C#做一名图书管理员。我正在使用.ACCDB
数据库来存储有关这些书籍的数据。
首先,我检索属于特定系列的bookIDs
:
sql.CommandText = "select * from BookTable where SeriesID = " +
DataClass.SeriesTableIndex;
它检索了BookIDs
20
和23
。这些是对应于DB中的BookIDs
的正确SeriesID
。
在此之后我的代码构建了下一个sql命令。我遗漏了命令的功能性建筑。它构建以下代码:
string sqlcommand = "select * from BookTable where BookID = 23 or 20"
我使用此命令获取书名:
sql.CommandText = sqlcommand;
它应该只返回bookWithID23
和bookWithID20
但它也返回bookWithID21
。我的测试数据库中只有3本书,但它以某种方式返回全部3本而不是系列中的2本。
我对SQL一无所知,所以它可能是一个简单的语法错误。
or
的正确语法是(https://www.w3schools.com/sql/sql_and_or.asp):
"BookID = 23 or BookID = 20"
另外你应该总是使用parameterized queries来避免SQL Injection,像这样:
sql.CommandText = "select * from BookTable where SeriesID = @SeriesID";
sql.Parameters.AddWithValue("@SeriesID", DataClass.SeriesTableIndex);
虽然直接指定类型并使用Value
属性比AddWithValue
更好:
sql.Parameters.Add("@SeriesID", SqlDbType.Int).Value = DataClass.SeriesTableIndex;