如何从数据库中获取字符串中的数据

时间:2015-02-19 14:43:34

标签: c# sql sql-server xml

我正在研究android客户端和.NET服务器应用程序,其中我将数据解析为xml然后转换为字符串然后将此字符串发送到android client.now我面临从xml格式的SQL Server获取数据的问题并将其转换为string.here是我的代码..

 UserLogin userLogin = converter.GetObjectFromXml<UserLogin>(xml);
    String query = @"Select StdBD.First_NameEn As name from TblStudentBioData As StdBD Join TblStudentDetail As StdDet ON StdBD.Student_ID = StdDet.Student_ID
       join TblClassSchedule As ClsSch on StdDet.ClassID = ClsSch.ClassSchID
     join TblClass As Cls on ClsSch.ClassID = Cls.ClassID 
     join TblSemAssigning As SemAs on SemAs.SemAssId = ClsSch.SemAssId
     join TblAcademicYear As Acd on SemAs.AcademicYearId = Acd.AcademicYearId
     where Acd.AcademicYearId = " + userLogin.userId + "FOR XML RAW('Student'),Root('Students'),Elements";
     String outputXml = General.ExecuteSimpleSelectQuery(General.connectionString, query, "Table user");
                   Console.WriteLine("xmllll = "+outputXml);

   class General
   {
    public static String ServerIp = "192.168.1.2";
    public static String ServerPort = "8060";
    public static String connectionString =    NetService2.Properties.Settings.Default.ConnString.ToString();

    public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
    {      
        SqlConnection conn = new SqlConnection(ConnectionString);            
        SqlCommand cmd = new SqlCommand(_Query,conn);
        SqlDataReader reader = null;          
        conn.Open();
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine("name = " + reader[0].ToString());
        }
        reader.Close();
        conn.Close();
        return "";
    }

输出:

enter image description here

通过使用此代码,我在SqlDataReader实例中获取数据但不在字符串中,因此有没有办法直接将数据转换为字符串或将SqlDataReader实例数据转换为字符串,所以我可以使用它。

我想要这样的输出:

String xml = "<Students>
  <Student>
    <name>Aliya</name>
  </Student>
  <Student>
    <name>Fahad</name>
  </Student>
  <Student>
    <name>iqra</name>
  </Student>
  <Student>
    <name>iqra</name>
  </Student>
  <Student>
    <name>khurram</name>
  </Student>
  <Student>
    <name>Zainab</name>
  </Student>
  <Student>
    <name>Fatima</name>
  </Student>
  <Student>
    <name>Fahad</name>
  </Student>
</Students>";

将这个硬编码的xml替换为xml,从数据库获取。

5 个答案:

答案 0 :(得分:1)

简单地将您的查询放入storedprocedure

 Create PROCEDURE yourprocedurename
 AS
 BEGIN
 Select StdBD.First_NameEn As name from TblStudentBioData As StdBD 
 Join TblStudentDetail As StdDet ON StdBD.Student_ID = StdDet.Student_ID
 join TblClassSchedule As ClsSch on StdDet.ClassID = ClsSch.ClassSchID
 join TblClass As Cls on ClsSch.ClassID = Cls.ClassID 
 join TblSemAssigning As SemAs on SemAs.SemAssId = ClsSch.SemAssId
 join TblAcademicYear As Acd on SemAs.AcademicYearId = Acd.AcademicYearId
 where Acd.AcademicYearId = " + userLogin.userId + "FOR XML 
 RAW('Student'),Root('Students'),Elements";
 END

从编码方面做这样的事情

public static String ExecuteSimpleSelectQuery(string ConnectionString, 
                                  string _Query, string DataTableName)
    {      
        SqlConnection conn = new SqlConnection(ConnectionString);            
        SqlCommand cmd = new SqlCommand("yourstoredprocedurename",conn);
        SqlDataAdapter SDA = new SqlDataAdapter();
        DataTable dt = new DataTable(DataTableName);
        conn.Open();
        cmd.CommandType = CommandType.StoredProcedure;
        SDA.SelectCommand = cmd;
        SDA.Fill(dt);
        conn.Close();
        return dt.Rows[0].ItemArray[0].ToString();
    }

希望它能为您提供所需的输出

答案 1 :(得分:1)

只需在DataTable中获取XML数据,它就会在第一个位置为您提供一个xml,然后将其转换为字符串。

    SqlConnection conn = new SqlConnection(yourConnectionString);            
    SqlCommand cmd = new SqlCommand(your query,conn);
    SqlDataAdapter SDA = new SqlDataAdapter();
    DataTable dt = new DataTable(DataTableName);
    conn.Open();
    SDA.Fill(dt);
    conn.Close();
    String xml =  dt.Rows[0].ItemArray[0].ToString();
    return xml;

答案 2 :(得分:0)

将所有记录加载到String.Join后,您可以使用List<string>

public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
{
    List<string> list = new List<string>();
    using(SqlConnection conn = new SqlConnection(ConnectionString))
    using (SqlCommand cmd = new SqlCommand(_Query, conn))
    {                
        conn.Open();
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                list.Add("name = " + reader.GetString(0));
            }
        }
    }
    return string.Join(Environment.NewLine, list);
}

但是,不要对sql命令使用字符串连接,因为你很容易受到sql注入攻击。因此,请勿将查询传递给方法ExecuteSimpleSelectQuery。而是使用sql-parameters。

答案 3 :(得分:0)

当您返回时,您的函数将始终返回空字符串&#34;&#34;每次调用函数后。尝试将您的功能更改为:

public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
    {      
        SqlConnection conn = new SqlConnection(ConnectionString);            
        SqlCommand cmd = new SqlCommand(_Query,conn);
            string result;
        conn.Open();
        var dt = new DataTable();
        dt.Load( cmd.ExecuteReader());


        using (StringWriter sw = new StringWriter()) {
        dt.WriteXml(sw);
         result = sw.ToString();
       }

        conn.Close();
        return result;
    }

答案 4 :(得分:0)

是的,您可以将列数据捕获到string。默认情况下,您的所有数据类型都将被视为object。这意味着你必须:

  • 使用SqlDataReader内置功能。<​​/ li>
  • 使用ToString()
  • 使用(string)as string演员。

在我提供一个示例之前,在尝试使用数据之前应该做一些事情null检查。

if(reader[0] != DBNull.Value)
{
     // Do Something...
}

原因是,如果您对数据执行某些操作,您将收到异常。另一个有用的事情,不是使用[0]而是["NameOfColumn"],而不是稍后维护代码,将使特定数据更易于阅读并查看其功能。

if(reader["NameOfColumn"] != DBNull.Value)
     example = reader["NameOfColumn"].ToString();

if(reader["NameOfColumn"] != DBNull.Value)
     example = (string)reader["NameOfColumn"];

example = reader["NameOfColumn"] as string;

这些是一些原始示例,如果失败则是最后一个将分配null。因此,您希望预测您的代码中可能存在冒泡。第一个例子,是最常见和最简单的。

但是,如果你想避免重复上述代码。

public static class DataReaderExtension
{
     public static string GetStringOrNull(this IDataReader reader, int ordinal)
     {
          var value = null;
          if(!reader.IsDBNull(reader.GetOrdinal(ordinal)
               reader.GetString(ordinal);

          return value;
     }

     public static string GetStringOrNull(this IDataReader reader, string columnName)
     {
          return reader.GetStringOrNull(reader.GetOrdinal(columnName));
     }
}

这些是几种不同的方法。希望这对你有所帮助。