I have a problem with fetching table names from SQL Server 2005. I have succeeded in fetching the table names but the problem is along with the table names VIEWS are also displaying. I need to display only the table names in a dropdown.
My code is:
...
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName="somedb";username=sa;password=1234";
Connection con = null;
Statement st = null;
ResultSet rslt = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
DatabaseMetaData md = con.getMetaData();
ResultSet rrs = md.getTables(null, null, "%", null);
while (rrs.next())
{
System.out.println(rrs.getString(3));
}
Here System.out.println(rrs.getString(3)); statement prints all the table names, but along with view names. I need to avoid printing view names. How can I do it?
you can query to meta data tables on MSSQL server. e.g. select * from sysobjects where xtype = 'u' ;here xtype is type of object and 'u' refers to the table type objects.. see MSSQL server documentation for syntax details
there are two areas:
1/ you not restricted on Db side for view the Metadata
2/ by using aliases return AliasName f.e. Select SomeColumNane as Count returns columnName Count
private ResultSetMetaData metaData; //variable
//intialize rslt("Select .....") and thenarter you can call from rstl
metaData = rslt.getMetaData();
//get Column Class (Varchar, Date, Double....)
String className = metaData.getColumnClassName(column + 1);// packed into try catch finally block
// get column count
int columnCount = metaData.getColumnCount();// packed into try catch finally block
//get Column Name
String columnName = metaData.getColumnName(column + 1);// packed into try catch finally block
Related
I am Retrieving some tables from database and storing those table names in a hashset. Code I am using to retrieve table is as follows
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
hash. add(rs. getString(3) ) ;
}
Now I have tables in a hash set.
Now I want to retrieve data from all these tables in a hash set for particular column 'student'. And put all values in a list. I want to retrieve all distinct values of column student in all these tables. Table may contain or may not contain this student column. If a table contains this column then I want to store its distinct values in a list. Please suggest how to do it.
Note that you can not extract table data using the databasemetadata. Databasemetadata will only provide you the details of table like name, columns, datatypes etc. You need to make the JDBC connection with the database and then need to fire the select query to get the desired result.
Below is the simple JDBC program to do so:
DatabaseMetaData md = conn.getMetaData();
// get tables from database
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
hash. add(rs. getString(3) ) ;
}
// getColumns of table 'tableName'
ResultSet rs2 = md.getColumns(null, null, tableName, null);
boolean found = false;
while (rs2.next()) {
String columnName = rs2.getString("COLUMN_NAME");
if (columnName.equalsIgnoreCase("student")) {
found = true;
break;
}
}
if (found) {
String driver = "provide the driver for database here like com.mysql.....";
String url = "provide the connection url here like jdbc://...."
String userName = "provide DB username"
String password = "provide DB username"
Class.forName(driver)
Connection conn = DriverManager.getConnection(url, userName, password)
Statement st = conn.createStatement();
Resultset rs3 = null;
// Now take the tableName from your hashset and pass it into below query.
String query = "select student from " + tableName;
rs3 = st.executeQuery(query);
While(rs3.next()) {
// Store the results anywhere you want by obtaining 'rs3.getString(1)'
}
}
Hope this resolves your problem. Please ignore typos in code if any.
I want to create an Access database connection using UCanAccess under Java 8. Here is my code:
String employeeName = endrollNameFields.getText();
String employeeAddress = endrollAddressFields.getText();
try
{
//------------CREATE CONNECTION TO DATA BASE--------------/
String DBPAD = "sourceFolder\\employeeTable2.mdb";
String DB = "jdbc:ucanaccess://" + DBPAD;
con = DriverManager.getConnection(DB, "", "");
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "select * from employeeTable2";
rs = st.executeQuery(sql);
rs.moveToInsertRow();
rs.updateString("Name", employeeName);
rs.updateString("Address", employeeAddress);
rs.insertRow();
st.close();
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql1 = "select * from employeeTable2";
rs = st.executeQuery(sql1);
JOptionPane.showMessageDialog(null, "<html>" + "<font color=\"#008000\">" + "<html><span style='font-size:1.5em'>Employee Successfuly Inserted to Data Base");
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, e1);
}
I made entries to my JTextField but when i click the button containing codes above this error message appears:
net.ucanaccess.jdbc.Ucanaccess SQLException:invalid cursor state: all columns must be set before insert
What is missing or lacking in my code?
UCanAccess uses HSQLDB as a "backing database", and HSQLDB requires that all columns in the insert row be given an explicit value before calling .insertRow(), including using rs.updateNull("ColumnName") to explicitly specify a NULL value. That's just the way it works.
This was discussed recently on SourceForge here. The requirement may be lifted in a future version of UCanAccess.
UPDATE
UCanAccess version 3.x, released in August 2015, has indeed removed the above requirement. Any columns not explicitly set in the insert row will contain the default value for the column (or NULL if the column is nullable and no default value is specified in the table definition).
I'm trying to retrieve result from MS SQL Server using netbeans.
the problem is when I retrieve Arabic words from the database I receive it as ????? .
Any one can help ?
and here is the code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:yasser");
System.out.println("test");
Statement sta = conn.createStatement();
String Sql = "select * from mainn order by id";
ResultSet rs = sta.executeQuery(Sql);
String res = null;
while (rs.next()) {
res = rs.getString("text");
System.out.println(res);
}
the data in the database is not inserted correctly. while inserting the arabic data into database you should choose UT-8. and change character set of database to AL32UTF8.
After a lot of searching i found a very good workaround which is to cast the column that is in arabic to varbinary and then to get it in your java project as bytes then creating a new string that takes the byte array as a constructor parameter which will use the arabic encoding "Windows-1256" to map the correct values of the arabic characters
here is a sample of the code
SQL select statement :
select cast([column_name] as varbinary(max)) from [table_name] where [condition]
java code :
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("select cast([column_name] as varbinary(max)) from [table_name] where [condition]");
while (rs.next()) {
byte[] tmp = rs.getBytes("column_name");
String cloumn_value = new String(tmp, "Windows-1256");
//cloumn_value arabic value
}
So this is my code
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/test";
//ResultSet rs = null;
PreparedStatement psmnt = null;
//FileInputStream fis;
connection = DriverManager.getConnection(connectionURL,"root","123");
psmnt = connection.prepareStatement("insert into Table1 (name, desc, r,g,b," +
"varR,varG,varB,skewnessR,skewnessG,skewnessB)values(?,?,?,?,?,?,?,?,?,?,?)");
final String text2 = setName.getText();
final String text3=setDesc.getText();
psmnt.setString(1,text2);
psmnt.setString(2,text3);
psmnt.setString(3,stringMeanR);
psmnt.setString(4,stringMeanG);
psmnt.setString(5,stringMeanB);
psmnt.setString(6,stringVarianceR);
psmnt.setString(7,stringVarianceG);
psmnt.setString(8,stringVarianceB);
psmnt.setString(9,stringSkewnessR);
psmnt.setString(10,stringSkewnessG);
psmnt.setString(11,stringSkewnessB);
//fis = new FileInputStream(f);
//psmnt.setBinaryStream(2, (InputStream)fis, (int)(f.length()));
int s = psmnt.executeUpdate();
psmnt.close();
connection.close();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else {
System.out.println("Unsucessfull to upload image.");
}
The problem is that i get the following error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, r,g,b,varR,varG,varB,skewnessR,skewnessG,skewnessB)values('','','105.59 , ' at line 1
desc is a reserved SQL keyword (used in order by foo desc). Change the name of the column you named "desc" (or escape it using backticks, but I would change the name to make it easier)
desc is a reserved keyword in SQL for describing an SQL table. As a result, if your column name is 'description' then it should be 'description'; not 'desc' as desc is reserved in MySQL for describing the table itself or showing the SQL code for the creation of the table.
The SQL DB has 110 tables and each table is having different column names. I have to loop through each table and fetch the data, so that I can write into a XML file.
For this, I created a new table called "MasterList" which holds all the 110 table names.
try{
// Connection for SQL Server.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://"+strDBServer+":1433;DatabaseName="
+ strDBName + ";" +
"User="+strDBUser+";Password="+strDBPassword+";";
Connection conn = DriverManager.getConnection(url);
if (conn != null) {
System.out.println("Connection Successful!");
}
//XML Transform
TransformerFactory tFactory = TransformerFactory.newInstance();
//Create a Statement object
Statement sql_stmt = conn.createStatement();
//Get List of all the tables present from Master table.
ResultSet rs = sql_stmt.executeQuery("SELECT TableName, Order FROM "
+ strDBName + ".[dbo].Master");
while (rs.next())
{
//Create a Statement object
Statement sql_stmt_1 = conn.createStatement();
String strTableName=rs.getString(1).trim();
int intOrder = rs.getInt(2);
hsMapTablesFromDB.put(strTableName,intOrder);
System.out.println("Hashmap --> " + hsMapTablesFromDB);
ResultSet rs_1 = sql_stmt_1.executeQuery("SELECT Name, LevelOfExistence, UniqueId FROM "
+ strDBName + ".[dbo]." + strTableName);
String strName = rs_1.getString(1).trim();
String strUnique = rs_1.getString(3).trim();
hsMapDataFromIndTable.put(strName,strUnique);
System.out.println("hsMapDataFromIndTable" + hsMapDataFromIndTable);
}
}
catch(Exception e){
e.printStackTrace();
}
As the column names in each table will be different, how to get the corresponding column names in "sql_stmt_1.executeQuery", so that once I get each record from the table, I have to insert it.
Like wise all the 110 tables data has to be inserted into XML file.
Please help me.
Thanks
Ramm
Try using following query for your column names in each table
select column_name from information_schema.columns
where table_name = 'YourTableName' //this will your iterated loop table name.
Using this query you will get all column names from your table add those column name in next query of that table.
then update the XML.