SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
myCommand.Connection.Open();
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (myReader.Read())
{
//表示有数据,你可以在这个地方顺便取出来.
}
myReader.Close();
myConnection.Close();
不能使用空白的对象或列名。如果必要,请使用一个空格。
为什么呢。
另外。因为打开一个连接后需要处理很多事务。不单是查询一次就算了。
所以我把代码改成如下。不知道那里错了。
string strConn = "user id=sa;password=sqlgoodboy;";
strConn += "initial catalog=Music;data source=127.0.0.1;";
strConn += "Connect Timeout=30";
SqlConnection myConn = new SqlConnection ( strConn ) ;
myConn.Open ();
for(int i = 0 ; i < 5 ; i ++)
{
string[] temp = new string[7];
temp[0] = "歌曲";
temp[1] = "url";
temp[2] = "歌手";
temp[3] = "歌手地区";
temp[4] = "歌手介绍";
temp[5] = "专辑";
temp[6] = "专辑语言";
string strSQLSongName = "SELECT song_id FROM songs where song_name = " + temp[0] + "\"";
SqlCommand SongName = new SqlCommand(strSQLSongName, myConn);
SqlDataReader myReaderSong = SongName.ExecuteReader();
if (myReaderSong.Read())
{
MessageBox.Show ("有数据");
}
MessageBox.Show ("没有数据");
}
SqlCommand SqlCmdInsertSingers = new SqlCommand(strInsertSingers, myConn);
SqlCmdInsertSingers.ExecuteNonQuery();string strSqlSingers2 = "SELECT singer_id FROM singers where singer_name = '" + temp[2] + "'";
SqlCommand CmdSingers2 = new SqlCommand(strSqlSingers2, myConn);
SqlDataReader myReaderSingers2 = CmdSingers2.ExecuteReader();
GetSingers_id = myReaderSingers2[0].ToString();
myReaderSingers2.Close();这里提示:在没有任何数据的时后进行无效的读取尝试。可是数据命名插入了阿。我在数据库中也看见数据了。