Using JDBC to work with an Access database containing Unicode (Punjabi, Hindi) data and table/column names - netbeans

My Access database has a table with a column that contains text in Punjabi. I am trying to work with that database from Java (NetBeans) using JDBC.
My code is :
private void b1ActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "D:\\PP.accdb";
Connection conn = DriverManager.getConnection(url);
System.out.println("Connection Successful");
Statement stmt = conn.createStatement();
stmt.execute("select * from Emp");
ResultSet rs = stmt.getResultSet();
if (rs != null)
{
String s1,s2;
s1=" ";
s2=" ";
while ( rs.next() )
{
JOptionPane.showMessageDialog(null ,rs.getString(2), "Output" ,JOptionPane.INFORMATION_MESSAGE );
}
}
stmt.close();
conn.close();
}
catch (Exception err) { System.out.println("ERROR: " + err); }
}

UCanAccess version 3.x, released in August 2015, now supports Unicode characters in table and column names. Note that such names need to be enclosed in square brackets, at least for UCanAccess v3.0.0, for example:
sql = "SELECT [रंग], inEnglish FROM hindi";
(Original Answer)
If, as stated in your comment to the question, you have an Access database with table and column names in Hindi or Punjabi then the two most common "direct" approaches for working with an Access database from Java won't work for you:
(1) The JDBC-ODBC Bridge
This is what you have been trying to use. Unfortunately, the JDBC-ODBC Bridge has never worked properly with the Access ODBC driver when the database contains Unicode text that includes characters above code point U+007F. This is true for both text data and table/column names. Also, the JDBC-ODBC Bridge is obsolete: it has been removed from Java 8 and is not supported. So, this option is a dead-end.
(2) UCanAccess
UCanAccess can successfully read/write Unicode text data, but the current (2.x) version cannot work with metadata (table/column names) containing Unicode characters above code point U+007F. Support for those characters in table/column names is planned for the next major release of UCanAccess (3.x), but no timeframe for such a release has been announced.
Other options:
Depending on the constraints under which you need to operate, you might consider one or more of the following workarounds.
You could move the data from the Access database into another database whose JDBC driver supports metadata in the Hindi and Punjabi languages.
You could build your application in C# instead of Java. (Visual Studio 2013 Community Edition is available for free.)
If you really must stick with Java and your data really must stay in an Access database then you could install Microsoft SQL Server Express Edition, create a "Linked Server" in SQL Server that points to the Access database (details here), then use the JDBC Driver for SQL Server to run queries against the Access database.

Related

Can DB2 DDL be generated using the IBM.Data.Db2 library

I'm new to Db2 and need to generate DDL for an existing table but don't have access to any tools. Is it possible to do this through the IBM.Data.DB2 library? I can get a datareader but only the field name is available. I work in a very restrictive environment hence the no tools statement. I don't know what operating system is used on the server. I'm a c#\vb.net developer and can execute commands of type text and stored procedures; however, creating stored procedures is very limited. I've done this sort of thing with Sql's SMO library but am not well versed with IBM.Data.DB2.
using (DB2Command dB2Command = new DB2Command($"SELECT * FROM {database}.{tableName}", dB2Connection))
{
dB2Command.CommandType = System.Data.CommandType.Text;
using (DB2DataReader dB2DataReader = dB2Command.ExecuteReader())
{
DataTable dataTable = dB2DataReader.GetSchemaTable();
foreach(DataRow dataRow in dataTable.Rows)
{
Console.WriteLine($"ColumnName: {dataRow.Field<string>("ColumnName")}\nColumnSize: {dataRow.Field<int>("ColumnSize").ToString()}\nNumericPrecision: { dataRow.Field<Int16>("NumericPrecision").ToString()}\nNumericScale: { dataRow.Field<Int16>("NumericScale").ToString()}\nDataType: {dataRow.Field<DbType>("ProviderType").ToString()}");
Console.WriteLine("");
}
}
}

Crystal reports - server and database

Im using visual studio 2010 + Sql Server 2008.
Im trying to show my reports using CR.. well when i try to use the system in my local machine, everything is ok.
I use store procedures to create reports.
The issue appears when i deploy the system in another PC.. A message appears asking for:
Server: // RETRIEVES ORIGINAL Server(Local)// Its not Correct i need to get Client Server
Database: // RETRIEVES ORIGINAL DB(Local)// Its not Correct i need to get Client DB
Username: I don't use any user , what user ?
Password: I don't use any password, what password?
i saw another solutions, but i can't find what's the data that i must use in Username or password. i use Windows autenthication to login to sql..
Thanks.
Regards.
Edit.. that's my code.. i can't use parameters, i don't receive any error. but system dont recognize the parameter that i send...
Dim NuevoReporte As New CReportNotaPorUsuario
Dim contenido As String
Dim ReportPath As String = My.Application.Info.DirectoryPath & "\CReportNotaPorUsuario.rpt"
Dim ConexionCR As New CrystalDecisions.Shared.ConnectionInfo()
contenido = Servicios.Funciones_Auxiliares.LeerArchivo(My.Application.Info.DirectoryPath & "\configuracion.txt")
ConexionCR.ServerName = Servicios.Funciones_Auxiliares.TextoEntreMarcas(contenido, "<server>", "</server>")
ConexionCR.DatabaseName = Servicios.Funciones_Auxiliares.TextoEntreMarcas(contenido, "<catalog>", "</catalog>")
ConexionCR.IntegratedSecurity = True
CrystalReportViewer1.ReportSource = ReportPath
'NuevoReporte.SetParameterValue("#cod_usuario", cbousuario.SelectedValue)
Dim field1 As ParameterField = Me.CrystalReportViewer1.ParameterFieldInfo(0)
Dim val1 As New ParameterDiscreteValue()
val1.Value = cbousuario.SelectedValue
field1.CurrentValues.Add(val1)
SetDBLogonForReport(ConexionCR)
It appears that you have separate servers and databases between the development and production environment. You need to make sure when you deploy your VS solution that the production server and database get referenced, not the development server and database.
There are some tutorials out there that can help you find a way to achieve this. Check out:
http://msdn.microsoft.com/en-us/library/dd193254(v=vs.100).aspx
Visual Studio 2010 Database Project Deploy to Different Environments
http://www.asp.net/web-forms/tutorials/deployment/advanced-enterprise-web-deployment/customizing-database-deployments-for-multiple-environments
EDIT: This seems to have evolved into a different issue than originally stated in the question. To dynamically get the connection string for CR from the text file, you will have to read teh text file first and put server name and database name into variables. Reading a text file, you can use something like string text = File.ReadAllText(#"C:\Folder\File.txt"); but you will need to extract server name and database name into variables. Then in order to use the variables in your connection string you use ConnectionInfo.Servername = variable1; and ConnectionInfo.DatabaseName = variable2.

How to read an .XLSX (Excel 2007) file using ADO.NET? I am finding "Could not find installable ISAM"-error

I need to work in .net 2.0. So I can't use OpenXML.
This is my source code and I have already Installed AccessDatabaseEngine.exe.
But still getting the exception:
"Could not find installable ISAM".
I have also tried "Extended Properties=Excel 8.0" in the connection string.
static void Main(string[] args)
{
DataSet dataSet = new DataSet();
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|Data Directory|\HSC.xlsx;Extended Properties=Excel 12.0;HDR=YES;");
OleDbDataAdapter dataAdapter= new OleDbDataAdapter("select * from [Sheet1$]", connection);
dataAdapter.Fill(dataSet);
}
According to Carl Prothman, that should be
Extended Properties="Excel 12.0 Xml;
-- http://www.connectionstrings.com/excel-2007
In more detail:
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Docs\\Book2.xlsx;Extended Properties='Excel 12.0 xml;HDR=YES;'");
Note the single quotes.
I prefer to use the Microsoft OpenXML 2.0 SDK for this kind of functionality. It has a really nice interface, and it does not put a demand on having Office installed on the machine reading the XLSX file which is a good thing.
I'm writing this from my mobile, so hard to provide a link, but a Google search should easily find it for you.
Give it a try. I think you will like it.
EDIT
If you have to use .NET 2.0, you can go for using the JET variant of the OleDb instead.
That means you will do something like this to connect:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source='" + filename + "';" +
"Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;\"";);
Then you can query it like in your example above:
OleDbDataAdapter objAdapter = new OleDbDataAdapter("select * from [Sheet1$]", connection);
Try it! Just note that Jet have some strange logic of deciding if a column is numeric or not. See the following SO questions for details: Problem with using OleDbDataAdapter to fetch data from a Excel sheet
You should make sure that the connection string looks like the following ( even if you are accessing microsoft excel version 10 ->
MyConnection = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source='D:\csharp-Excel.xls';Extended Properties='Excel 12.0 Xml;HDR=Yes;'");

Is it possible to retrieve connection string inside DDL generation template in VS2010?

I am playing around with creating a T4 template for the "DDL Generation Template option" (model first) process in Visual Studio 2010 RC. Is it possible to retrieve the connection string that is associated with that process? If I right click on the .edmx file and choose "Generate Database from Model..." I have the option of choosing a data connection. That connection string is saved to the app.config (assuming that the option is checked). So I am wondering if it is possible to retrieve that connection string inside the T4 template. I would like to generate different information from the template based on the connection string.
More generally, is it possible to get any context information in this situation? So far, the only thing I have successfully retrieved is the .NET data provider name.
Note - I have studied the ideas provided by Craig but am only getting the name of the IDE (devenv.exe), which quite possibly means I am just doing something wrong.
In case this helps anyone else, here is a snippet I created to read the Entity Framework connection string from inside T4. You pass it the model name (which is also the name of the connection string). It finds and parses just the connection bit I need. It also throws helpful errors when it does not succeed.
To use:
A. Paste this at the top of your template if you aren't already referencing these assemblies:
<## assembly name="EnvDTE" #>
<## assembly name="System.Configuration" #>
B. Paste this ugly (but compact) code at the end of your template:
<#+
string GetEFConnectionString(string modelName)
{
string file = null, key = "provider connection string=\"";
foreach (EnvDTE.ProjectItem item in ((EnvDTE.Project)((Array)((EnvDTE.DTE)((IServiceProvider)this.Host).GetService(typeof(EnvDTE.DTE))).ActiveSolutionProjects).GetValue(0)).ProjectItems)
if (System.Text.RegularExpressions.Regex.IsMatch(item.Name, "(app|web).config", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) {
file = item.get_FileNames(0); break;
}
if (file == null) throw new Exception("config file could not be found");
var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = file }, System.Configuration.ConfigurationUserLevel.None);
var cn = config.ConnectionStrings.ConnectionStrings[modelName];
if (cn == null) throw new Exception(modelName + " connection string could not be found");
string s = cn.ConnectionString;
int pos = s.IndexOf(key,StringComparison.OrdinalIgnoreCase);
if (pos<0) throw new Exception("could not find value '" + key + "' inside connection string");
pos += key.Length;
int pos2=s.IndexOf('"',pos);
if (pos2 < 0) throw new Exception("could not find ending \" in connection string");
return s.Substring(pos,pos2-pos);
}
#>
C. Use it like such:
using(var connection = new SqlConnection(GetEFConnectionString("Database"))) {
..
}
I posted my question on one of the MSDN forums and got a response from Lingzhi Sun who pointed me in the direction of a couple of links at skysanders.net. The second of these links has a very nice example of getting to the app/web.config file and, specifically the part I wanted, the connection strings. It doesn't give any information on the specific connection string for the scenario I described in the original question, but this gets me close enough.
Accessing app.config/web.config from T4 template
Accessing app.config/web.config from T4 template - Take 2
Well, the EF connection string will always have the same name as the model, right? The DB connection string will be embedded in the EF connection string. So I'd say you should be able to get it, at least indirectly, via the EF connection string.
Because you're not running in the assembly, have to specify the config file name.
So it would be something like:
var config = ConfigurationManager.OpenExeConfiguration(name);
var cs = config.ConnectoinStrings[modelName];
Note that name, here, is supposed to be an EXE name. But in the IDE, your config fine is going to be called App.config rather than MyApp.dll.config. So you may have to play around with this to get it to work -- try using "App" as the EXE name!
Worst case is open it as a file and then use the config manager.

insert into sql query in wpf

Hello everyone i am new in wpf. so i have got problems with it. if you help me, i will be so pleased. thanks everyone in advance.
My problem is, can not insert into name inside database in wpf. how can i fix it? my codes as follows;
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
string SqlString = "Insert Into UserInformation(name) Values (?)";
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Cell.mdb;Persist Security Info=True"))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("name", textBox1.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{ }
}
Try to use cmd.Parameters.AddWithValue("#name", textBox1.Text);
Is it opening the right database file? As people have suggested in the comments, set Visual Studio to break on first-chance exceptions, or remove the exception handling. The database file needs to exist, and you need the appropriate JET drivers.
I've tried your code and it works without any problems here (in a WPF application or otherwise). Using named parameters instead of a question mark was a good suggestion, but it doesn't appear to be the problem. (I have Office 2007 and .NET 3.5 SP1 installed, but I doubt that matters).
Are you using a WPF browser application (cbap)? Because you won't be able to access the local file system (and thus the database) if you are. WPF browser applications run with isolated permissions, much like a Silverlight browser application.
The problem here seams to be the parameter. In the command text you don't specify its name, but when you add it, it has a name. Change command text to :
Insert Into UserInformation(name) Values (#name)
In line:
cmd.Parameters.AddWithValue("name", textBox1.Text);
the parameter name should stay without # .