I am having problems in picking the right collation / locale on a Windows Embedded Compact Edition 6.0 device.
I am using .NET compact framework 2.0 on said device.
I am having difficulties inserting the letters ŠĐČĆŽšđčćž in the database.
I am getting a PlatformNotSupported exception.
Available locales on the CE device does not list Croatian or anything similar.
When i pick SQL_Latin1_General_CP1_CI_AS as the database/table/column collation it works (in combination with the English (US) locale on the device, but i can't insert previous letters.
The same collation, using Management studio 2008, from a Windows 7 desktop PC, correctly accepts all those letters.
What am I doing wrong?
I was not able to duplicate this on our older SQL 2000 Server, and I would certainly hope that SQL Express 2008 has more for dealing with multilingual issues than SQL 2000.
I used the following code as my test:
private const string jp2code = "jp2code.net";
private void Form1_Activated(object sender, EventArgs e) {
string croatianIn = "ŠĐČĆŽšđčćž";
string croatianOut = TestCroatian(croatianIn);
Console.WriteLine(String.Compare(croatianIn, croatianOut));
}
private string TestCroatian(string input) {
string result = null;
string sql = "INSERT INTO SUITEMSG (MsgFrom, [Message]) VALUES (#MsgFrom, #Message);";
using (SqlCommand cmd = new SqlCommand(sql, Data.Connection)) {
cmd.Parameters.Add("#MsgFrom", jp2code);
cmd.Parameters.Add("#Message", input);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
sql = "SELECT [Message] FROM SUITEMSG WHERE MsgFrom=#MsgFrom;";
using (SqlCommand cmd = new SqlCommand(sql, Data.Connection)) {
cmd.Parameters.Add("#MsgFrom", jp2code);
cmd.Connection.Open();
result = cmd.ExecuteScalar().ToString();
}
return result;
}
Both the input and the output were identical.
Are you sure there isn't something else you are doing?
Can you update your question to post a short code example like I have done above to show what does NOT work?
Related
please help. in Visual Studio 2017 and SQL localDB - WinForm learns and makes a small application. Form (Textbox), where "name, surname, address, city, phone and email" is written in Czech language containing "ěščřžýáíé" ". Everything is stored in the database (nvarchar) in order. Everything OK.
In Form2 I have another form where Combobox calls a "surname" and it has to fill in the phone and e-mail automatically from the database. If the surname is without the character "ěščřžýáíé", everything will be displayed correctly. If it contains "ěščřžýáíé", only the last name will be displayed, but the phone and email will not be loaded into the TextBox.
The code sample (without ěščřžýáíé) works perfectly:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\newtest.mdf;Integrated Security=True");
string sql = "select * from test111 WHERE firmadat ='" + prijmeniComboBox.Text + "'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
while (myreader.Read())
{
string rollno = myreader.GetInt32(0).ToString();
string name = myreader.GetString(1);
string telephone = myreader.GetString(3);
string email = myreader.GetString(4);
textBox1.Text = rollno;
telefonTextBox.Text = telephone;
emailTextBox.Text = email;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Thank you for your help.
The problem is probably here:
string sql = "select * from test111 WHERE firmadat ='" + prijmeniComboBox.Text + "'; ";
Here you take your Unicode string and you concatenate it into a SQL string that is not a Unicode string. I would tell you how to get it working as you intended but this is a really really dangerous way to write SQLs. Someone at kids' toy maker VTech wrote SQLs this way and enabled a hacker to download millions of images of children taken by vtech devices. If one of my developers wrote SQL like this they would be subject to disciplinary action, possibly being fired.
I strongly recommend that you use parameterized SQLs; any number of internet resources will show you how, such as http://bobby-tables.com - it will also solve the problem of getting no results when searching using a search term that contains non-ASCII characters
Take a look at http://dapper-tutorial.net ; using dapper will not only take care of the parameterizing for you, but make your database life easier by reducing your code to just a couple of lines, something like:
using(SqlCommand x = new SqlCommand(conn)
{
var p = x.Query(
"select * from test111 WHERE firmadat = #a",
new { a = prijmeniComboBox.Text }
);
firstNameTextBox.Text = p.FirstName; //or what the column is called on db
...
}
You just write your sql, use #namedParameter placeholders and supply an anonymous object with properties named after the placeholders. Dapper does the rest. If you have a Person class in your project you can even get dapper to create it and populate it for you
I've built a query that involves joining 2 tables that exist in separate databases. I'd like to run this query within my .NET Core 2.1 application. Here is what I've got:
Query:
INSERT INTO Database2.dbo.Table2
SELECT * FROM Table1
WHERE Col1 = 5
This query works just fine within SQL Operations studio.
C#:
using(var context = ConnectionHelper.getContext(dbInfo))
{
string MySQLQuery =
" INSERT INTO Database2.dbo.Table2 " +
" SELECT * FROM Table1 " +
" WHERE Col1 = 5 ";
try
{
context.Database.ExecuteSqlCommand(MySQLQuery);
}
catch(Exception e)
{
Console.WriteLine(e.Message); // This doesn't get called, the query doesn't throw an error.
}
}
When I run the query through .NET Core, nothing happens. I expect ~1000 rows to be written to Database2.dbo.Table2, but 0 are written. No Error message is logged, so .NET Core seems to think it succeeded in performing the given SQL query. I'm assuming the error is being caused by my reference to Database2.
The solution to the problem was to avoid using ExecuteSqlCommand within a given context. Since I didn't specifically need any features of EF for this query, I ended up using SqlCommand.ExecuteNonQuery() from the System.Data.SqlClient library. Here's a working example:
using (SqlConnection con = new SqlConnection(< your connection string >))
{
con.Open();
SqlCommand command = new SqlCommand();
command.CommandText = " SQL STATEMENT HERE ";
command.Connection = con;
command.ExecuteNonQuery();
}
i want to store date and time in SQL Server 2012 using asp.net but generate some error "Conversion failed when converting date and/or time from character string."
protected void btn Submit_Click(object sender, EventArgs e)
{
lbldate.Text = Convert.ToDateTime(this.txtdate.Text).ToString("dd/MM/yyyy");
lbltime.Text = Convert.ToDateTime(this.txttime.Text).ToLongTimeString();
TimeSpan time = new TimeSpan();
time.ToString();
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-O6SE533;Initial Catalog=Datertime;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
SqlCommand cmd = new SqlCommand("insert date,time into DateTimedemo values('" +txtdate.Text + "','"+txttime.Text+"')", con);
con.Open();
int r = cmd.ExecuteNonQuery();
if (r > 0)
{
Response.Write("success");
}
else
{
Response.Write("failed");
}
}
Use parameterized SQL instead of building the SQL dynamically. This avoids SQL injection attacks and string formatting differences, as well as making the code clearer.
Additionally, I believe both "date" and "time" are keywords in T-SQL, so you should put them in square brackets when using them as field names.
You should attempt to perform as few string conversions as possible. Without knowing exactly what your web page looks like it's hard to know exactly how you want to parse the text, but assuming that Convert.ToDateTime is working for you (sounds worryingly culture-dependent to me) you'd have code like this:
protected void btn Submit_Click(object sender, EventArgs e)
{
// TODO: Ideally use a date/time picker etc.
DateTime date = Convert.ToDateTime(txtdate.Text);
DateTime time = Convert.ToDateTime(txttime.Text);
// You'd probably want to get the connection string dynamically, or at least have
// it in a shared constant somewhere.
using (var con = new SqlConnection(connectionString))
{
string sql = "insert [date], [time] into DateTimeDemo values (#date, #time)";
using (var cmd = new SqlCommand(sql))
{
cmd.Parameters.Add("#date", SqlDbType.Date).Value = date;
cmd.Parameters.Add("#time", SqlDbType.Time).Value = time.TimeOfDay;
int rows = cmd.ExecuteNonQuery();
string message = rows > 0 ? "success" : "failed";
Response.Write(message);
}
}
}
I've guessed at what SQL types you're using. If these are meant to represent a combined date and time, you should at least consider using a single field of type DateTime2 instead of separate fields.
I have a simple SQL code that returns one record but when I execute it from Java, it does not return the string portions of the record, only numerical. The fields are VARCHAR2 but do not get extracted into my resultset. Following is the code. The database connectivity portion has been edited out for posting in the forum but it does connect. I have also attached the output. Any guidance would be appreciated as my searches on the web have returned empty. -Greg
package testsql;
import java.sql.*;
public class TestSQL {
String SQLtracknbr;
int SQLtracklength;
int numberOfColumns;
String coltypename;
int coldispsize;
String SQLschemaname;
public static void main(String[] args)
throws ClassNotFoundException, SQLException
{
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
String url = "jdbc:oracle:thin:#oracam.corp.mot.com:1522:oracam";
String SQLcode = "select DISTINCT tracking_number from sfc_unit_process_track where tracking_number = 'CAH15F6WW9'";
System.out.println(SQLcode);
Connection conn =
DriverManager.getConnection(url,"report","report");
conn.setAutoCommit(false);
try (Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(SQLcode)) {
ResultSetMetaData rsmd = rset.getMetaData();
while (rset.next()) {
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);
String coltypename = rsmd.getColumnTypeName(1);
int coldispsize = rsmd.getColumnDisplaySize(1);
String SQLschemaname = rsmd.getSchemaName(1);
String SQLtracknbr = rset.getString(1);
int SQLtracklength = SQLtracknbr.length();
if (SQLtracknbr == null)
System.out.println("NULL**********************.");
else
System.out.println("NOT NULL.");
System.out.println("numberOfColumns = " + numberOfColumns);
System.out.println("column type = " + coltypename);
System.out.println("column display size = " + coldispsize);
System.out.println("tracking_number = " + SQLtracknbr);
System.out.println("track number length = " + SQLtracklength);
System.out.println("schema name = " + SQLschemaname);
}
}
System.out.println ("*******End of code*******");
}
}
The result of what is executed in Java is below:
run:
select DISTINCT tracking_number from sfc_unit_process_track where tracking_number = 'CAH15F6WW9'
NOT NULL.
numberOfColumns = 1
column type = VARCHAR2
column display size = 30
tracking_number =
track number length = 0
schema name =
*******End of code*******
BUILD SUCCESSFUL (total time: 0 seconds)
This seems to be caused by an incompatibility between the driver you're using, ojdbc7.jar, and the version of the database you're connecting to, 9i.
According to the JDBC FAQ section "What are the various supported Oracle database version vs JDBC compliant versions vs JDK version supported?", the JDK 7/8 driver ojdbc7.jar that you're using is only support for Oracle 12c.
Oracle generally only support client/server versions two release apart (see My Oracle Support note 207303.1), and the Oracle 12c and 9i client and server have never been supported either way around. JDBC is slightly different of course, but it may be related, as drivers are installed with the Oracle software.
You will have to upgrade your database to a supported version, or - perhaps more practically in the short term - use an earlier driver. The Wayback Machine snapshot of the JDBC FAQ from 2013 says the 11.2.0 JDBC drivers - which includes ojdbc6.jar and ojcbd5.jar - can talk to RDBMS 9.2.0. So either of those ought to work...
I just try simple joins with C# using oracle db. Should be no big deal. But it ALWAYS fails. It works in MS-Access. Where is the problem ? (OleDb or Odbc makes no difference here, I tried both)
Edit:
Might Oracle version be the problem ? (seems we are using 8.1.7.0.0 and 8.1.5.0.0 modules)
Code:
using System;
using System.Data.Odbc;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string n = Environment.NewLine + "--------------------------------" + Environment.NewLine + Environment.NewLine;
// connect
string connectionString = "dsn=TEST;uid=read;pwd=myPwd";
OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();
// select (key is actually text not numeral)
string query = "select * from INFOR.ZEITEN where (KEY = 0)";
query = "select a.KEY, b.GREG from INFOR.ZEITEN a inner join INFOR.ZEITEN b on (a.AUSWEIS = b.AUSWEIS) where (a.KEY like '1')";
try
{
query = query.Replace(Environment.NewLine, " ");
Console.WriteLine(n + query);
OdbcCommand command = new OdbcCommand(query, connection);
OdbcDataReader reader = command.ExecuteReader(); // throws exception
if (reader != null)
Console.WriteLine(n + "success, now read with reader!");
}
catch (Exception e)
{
Console.WriteLine(n + e.Message + n + e.StackTrace);
}
// wait
Console.ReadKey();
}
}
}
Output:
And the successful, simple select:
ANSI joins (ex. inner join) were first supported in 9i. You will need to use the old syntax:
select a.KEY, b.GREG
from INFOR.ZEITEN a,
INFOR.ZEITEN b
where (a.AUSWEIS = b.AUSWEIS)
and (a.KEY like '1')
Note that the like operator is equivalent to = in this case, but you probably know that
I think the KEY is numeric then you can't use LIKE. It is because the WHERE KEY = 0 works fine.
The word key is a reserved word. That means that it is a very poor choice for an identity. You need to escape it with a double quote. This might work:
query = "select a.\"KEY\", b.GREG
from INFOR.ZEITEN a inner join
INFOR.ZEITEN b
on (a.AUSWEIS = b.AUSWEIS)
where (a.\"KEY\" like '1')";
I am guessing the \" will work in this context, but there might be another method to insert this character.
What's the error? Could you edit your question and add the actual error the system's throwing at you?
Firstly, I would personally recommend using the ODP .NET (Oracle Data provider for .NET). You can download the latest version for Oracle 12c here. Or look it up for the version you need.
ODBC is a very old driver written in C and works using the native Windows RPC technique.
For full .NET support you're better off with ODP .NET.
Secondly, check if you have any constraints on the tables that's causing the sql to fail.