2017-07-14 97 views
-3

我不能轉換這個字符串,任何人都可以幫助我嗎?爲什麼我無法將字符串轉換爲DateTime?

[WebMethod] 
public void InsertUsuario(string usuario, string senha, string nome, string dtnasc, string fone, string email, int oab, string endereco, string bairro, string cep, int codcidade, string cpf, string cnpj) 
{ 
    using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) 
    { 
     string chav = "asfasdf"; 
     DateTime d = DateTime.ParseExact(dtnasc, "yyyy'-'MM'-'dd'T'HH':'mm", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); 

     SqlCommand command = new SqlCommand("INSERT Into Usuarios (IdUsuario, Usuario, Senha, Nome, Chave, DtNasc, Fone, Email, OAB, Endereco, Bairro, CEP, CodCidade, CPF, CNPJ) VALUES ((Select MAX(idusuario)+1 from Usuarios), '" + usuario + "', '" + senha + "', '" + nome + "', '" + chav + "', '"+d+ "', '" + fone + "', '" + email + "', " + oab + ", '" + endereco + "', '" + bairro + "', '" + cep + "', " + codcidade + ", '" + cpf + "','"+cnpj+"')"); 

     //command.Parameters.Add("@dtnasc", SqlDbType.DateTime).Value = DateTime.Now; 
     command.Connection.Open(); 
     command.ExecuteNonQuery(); 
    } 
} 

這是出現錯誤:

System.FormatException:Cadeia德CARACTERESÑãöFOI reconhecida como的日期時間v á利多。
em System.DateTimeParse.ParseExact(String s,String format,DateTimeFormatInfo dtfi,DateTimeStyles style)
em OniPresenteAPI.oni.InsertUsuario(String usuario,String senha,String nome,String dtnasc,String fone,String email,Int32 oab ,字符串endereco,字符串的Bairro,字符串CEP,的Int32 codcidade,CPF的字符串,字符串CNPJ)

+6

*請*使用參數化的SQL。對於SQL注入攻擊,您是**開放**。不僅如此,如果你使用參數化SQL,它甚至可以解決這個問題,因爲將字符串連接在一起形成一個SQL腳本非常容易打破錯誤,就像你得到的錯誤一樣。 – Siyual

+2

除了sql注入問題,什麼字符串不能被解析?你甚至沒有示例。 –

+0

dtnasc的確切值是什麼? – dazedandconfused

回答

0

基於要傳遞的的日期字符串註釋的問題 「1991年12月21日00:00」分成DateTime.ParseExact()。異常中的線索正在爆炸,因爲第二個參數format參數不正確。您的參數是"yyyy'-'MM'-'dd'T'HH':'mm"。正確的格式應該是"yyyy-M-dd hh:mm"。有文檔here的讀操作,具體地,本領域:

的 DateTime.ParseExact(字符串,字符串,的IFormatProvider,DateTimeStyles) 方法解析日期的字符串表示,它必須是在所定義的格式 由格式參數。它還要求日期 和s中的時間元素按格式指定的順序出現。如果s 與format參數的模式不匹配,並且style參數定義了任何 變體,則該方法拋出FormatException。

這是我的工作例如:

using System; 
using System.Globalization; 
public class Program 
{ 
    public static void Main() 
    { 
     string dateAsAString = "1991-12-21 00:00"; 
     try 
     { 
      DateTime d = DateTime.ParseExact(dateAsAString, "yyyy-M-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); 
      Console.WriteLine("The correct Date is " + d.ToString()); 
     } 
     catch (FormatException) 
     { 
       Console.WriteLine("{0} is not in the correct format.", dateAsAString); 
     } 
    } 
} 

的工作dotnetfiddle,以及你與format字符串玩耍。