2016-03-15 67 views
-6

我的連接字符串:C#返回值

string connection = @"Provider=Microsoft.ACE.OLEDB.12.0;" + 
    @"Data Source=\\reso-fs-2\allusers\Student_Home\20350657\Documents\clicker.accdb;" + 
    @"Jet OLEDB:Database Password=" + "password" + ";"; 

OleDbConnection con = new OleDbConnection(connection); 

所以我有這個疑問在C#中OLEDB:

string query = "SELECT stats_best FROM Users WHERE username="+GameForm.username; 

我想獲取從 'stats_best' 的價值和將其保存到一個字符串中。 我已經建立了連接和所有。我只需要從查詢中返回一個值。 我該怎麼做?

+3

你讀過那篇關於創建和執行命令什麼?請學習一些教程,因爲這是錯誤的學習方法... –

+0

[如何創建和執行返回行的SQL語句](https://msdn.microsoft.com/zh-cn/library/fksx3b4f.aspx ) –

+0

或http://stackoverflow.com/a/21709663/993547。 –

回答

0

請閱讀this文章,但無論如何,你可以使用這個

public string Test(string userName, string connectionString, out string dbErrorMessage) 
    { 
     string result = null; 
     dbErrorMessage = null; 
     try 
     { 
      using (SqlConnection connection = new SqlConnection(connectionString)) 
      { 
       connection.Open(); 
       SqlCommand cmd = connection.CreateCommand(); 
       cmd.Parameters.Add(new SqlParameter("@UserName", userName)); 
       cmd.CommandText = "SELECT stats_best FROM Users WHERE username= @UserName"; 
       result = cmd.ExecuteScalar().ToString(); 
      } 
     } 
     catch (Exception ex) 
     { 
      dbErrorMessage = ex.Message; 
     } 
     return result; 
    } 

和方法的用法:

string dbErrorMessage = null; 
Test(GameForm.username, connectionString, out dbErrorMessage); 
+0

這似乎執行,但它不會從數據庫中返回值。 – Pawel

+0

你檢查過你的'ConnectionString'嗎? – SeM

+0

我無法從這裏檢查您的連接字符串,請檢查它是否有效。執行的結果是什麼? – SeM

0
private string Func(GameForm GameForm){ 

       DataTable table ; 
       string connectionString = //"connection string"; 
       string query = "SELECT stats_best FROM Users WHERE username=" + GameForm.username; 

       SqlConnection sqlConnection = new SqlConnection(connectionString);   
       SqlCommand sCmd = new SqlCommand(query, sqlConnection); 
       sqlConnection.Open(); 

       SqlDataAdapter dataAdapt= new SqlDataAdapter(sCmd); 

       dataAdapt.Fill(table); 
       sqlConnection.Close(); 
       dataAdapt.Dispose(); 
       return table.ToString(); 
      } 
+0

看到[this](https://sophosnews.files.wordpress.com/2015/10/xkcd327-1000.jpg?w=640)附件 – SeM

+0

不是每個使用Sql的程序都需要注意「sql注入」它取決於使用該程序或程序的用戶的大多數用戶。但仍然有趣的il分享它 –