Cyrillic value insert error in SqlParameter on mono - sql-server

Next code snippet throws exception if I use as value in #Name string with cyrillic characters. If I use latin chars it works fine. On Windows host with .Net 4.0 works fine. But on Ubuntu 14.04 with last mono it has error. SQL server MS SQL 2014.
StringBuilder sb = new StringBuilder();
sb.AppendLine("INSERT INTO [MyTable]([Name],[ID]) ");
sb.AppendLine("VALUES(");
sb.Append("#Name, ");
sb.Append("#ID)");
SqlConnection sqlConnection =
new SqlConnection(connStr);
try
{
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand(sb.ToString(), sqlConnection);
SqlParameter sqlParameter = null;
var msg = "Имя";
sqlParameter = new SqlParameter("#Name", SqlDbType.VarChar, 0, "Name");
sqlParameter.Value = msg;
sqlCommand.Parameters.Add(sqlParameter);
sqlParameter = new SqlParameter("#ID", SqlDbType.BigInt, 0, "ID");
sqlParameter.Value = 39;
sqlCommand.Parameters.Add(sqlParameter);
sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
var a = 0;
}
finally
{
sqlConnection.Close();
}

Try
sqlParameter = new SqlParameter("#Name", SqlDbType.NVarChar, 0, "Name");
instead of
sqlParameter = new SqlParameter("#Name", SqlDbType.VarChar, 0, "Name");

Related

Save list of Arabic strings in database

I have a c# program. I have list of string. The elements of that list in Arabic. When I try to save the elements of list in database I see symbols "??????"
Here my code
List<string> _names = new List<string>()
{
"ذهب",
"قال",
"تعال",
"متى",
"البرمجة",
"احمد"
};
SqlConnection connection = new SqlConnection("Server=DESKTOP-JRS3DQ4; DataBase=Library_DB; Integrated Security=true");
connection.Open();
for (int index = 0; index < _names.Count; index++)
{
SqlCommand command = new SqlCommand("INSERT INTO tbl_names (id,name) VALUES ('" + index + "', '" + _names[index] + "')", connection);
command.ExecuteNonQuery();
}
connection.Close();
How I can solve this problem please?
Most likely, your problem is coming from inserting strings (as varchar) instead of NVarchar.
Your code will work more-reliably, safer & faster if you define a parameterized query and parameters before you run your loop:
List<string> _names = new List<string>()
{
"ذهب",
"قال",
"تعال",
"متى",
"البرمجة",
"احمد"
};
SqlConnection connection = new SqlConnection("Server=DESKTOP-JRS3DQ4; DataBase=Library_DB; Integrated Security=true");
connection.Open();
SqlCommand command = new SqlCommand("INSERT INTO tbl_names (id,name) VALUES (#Id, #Name)", connection);
command.Parameters.Add("#Id", SqlDbType.Int);
command.Parameters.Add("#Name", SqlDbType.NVarChar, 20); //size and type must match your DB
for (int index = 0; index < _names.Count; index++)
{
command.Parameters["#Id"].Value = index;
command.Parameters["#Name"].Value = _names[index];
command.ExecuteNonQuery();
}
connection.Close();
One last note: This will not help unless your DB has the Name column defined as a NVarChar.

Local SQL Server connection fail

I'm trying to connect to a local SQL Server database file and do not know if connection string is right:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ma\Documents\mydb.mdf;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT plataform FROM plataforms", con);
DataSet myDataSet = new DataSet();
sda.Fill(myDataSet);
I have such code wrapped in a try catch and always throws this exception:
Reference to object not established as an instance of an object
What's wrong?
EDIT:
Sorry, I have been commenting code to see what line arises such error and it's the following:
DataRowCollection drc = myDataSet.Tables["plataforms"].Rows;
Sorry, I made a wrong question.
I think You must open connection before Fill
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ma\Documents\mydb.mdf;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT plataform FROM plataforms", con);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = sda;
DataSet myDataSet = new DataSet();
try {
con.Open();
sda.Fill(myDataSet);
} catch (Exception ex) {
throw (ex);
} finally {
con.Close();
}
you can try this code.

Oledb connection in visual basic function call

please explain line by line what this particular code which is being used in a button click to store 3 variables is doing?
OleDbCommand Cmd = new OleDbCommand("INSERT_DEPT", con);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("PRETURN", OleDbType.VarChar, 30).Direction =ParameterDirection.ReturnValue;
Cmd.Parameters.Add("PDEPTNO", OleDbType.SmallInt, 30).Direction = ParameterDirection.Input;
Cmd.Parameters["PDEPTNO"].Value = txtDeptno.Text.ToString();
Cmd.Parameters.Add("PDNAME", OleDbType.VarChar, 30).Direction = ParameterDirection.Input;
Cmd.Parameters["PDNAME"].Value = txtDName.Text.ToString();
Cmd.ExecuteNonQuery();
String Str = Convert.ToString(Cmd.Parameters["PRETURN"].Value);
MessageBox.Show(Str);

c# error "Procedure 'spReturnLastRowNoteID' expects param '#noteid', which was not supplied." though I don't have input parameter in sp

ALTER PROCEDURE dbo.spReturnLastRowNoteID
(#noteid int OUTPUT)
AS
SET NOCOUNT ON
SELECT #noteid = NoteID
FROM NoteTable
WHERE NoteID = IDENT_CURRENT('NoteTable')
RETURN #noteid`
I don't think there is a problem in my sp and code but I'm not sure why i'm getting the error:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sqlSearchCommand = "spReturnLastRowNoteID";
SqlCommand command = new SqlCommand(sqlSearchCommand, connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter noteid = command.Parameters.Add("#noteid", SqlDbType.Int);
noteid.Direction = ParameterDirection.ReturnValue;
command.ExecuteNonQuery();
lastnoteid = (int)command.Parameters["#noteid"].Value;
}
Try setting the parameters direction to Output.
noteid.Direction = ParameterDirection.Output;

Read XML from SQL Server using OleDbDataReader

I'm stuck trying to read XML data from SQL Server using OleDb.
private static void Main(string[] args){
var con = new OleDbConnection("Provider=SQLNCLI11.1;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Temp");
var cmd = new OleDbCommand(
"SELECT [Id] ,[Description] FROM [Temp].[dbo].[SomeTable] where [Id]= 1 for xml path, root('root')", con);
con.Open();
byte[] result = null;
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read()){
result = (byte[]) reader[0];
}
MemoryStream stream = new MemoryStream(result);
stream.Position = 0;
XmlDocument doc = new XmlDocument();
doc.Load(stream);
Console.Out.WriteLine(doc.OuterXml);
}
It fails saying that data is malformed. If I convert the byte array to string I see a lot of "strange " characters. What I'm doing wrong?
Since the result is direct XML I believe you are facing issue.You need to get the result in row-set instead of scalar.
Read as String, Use LoadXML instead of stream.
Below is the code I changed.
private static void Main(string[] args)
{
var con = new OleDbConnection("Provider=SQLNCLI11.1;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Temp");
var cmd = new OleDbCommand(
"Select (SELECT [Id] ,[Description] FROM [Temp].[dbo].[SomeTable] where [Id]= 1 for xml path, root('root')) AS XML", con);
con.Open();
string result = string.Empty;
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read())
{
result = reader[0].ToString();
}
con.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
Console.Out.WriteLine(doc.OuterXml);
}

Resources