Is the SQLserver name a STATIC IP?
Dear all,
I'm using an AZURE Mobile Service (an Android App) with a SQL DB. The App shows data of the SQL DB.
I need to use the SQL connection in a program that writes datas on it (.NET in c# program)
I got a SQL server name (10 chars lowercase), i.e. 'abcdefghil'. My program connection string is like this:
this.scsBuilder = new SDSqlC.SqlConnectionStringBuilder();
this.scsBuilder["Server"] = "tcp:abcdefghil.database.windows.net,1433";
this.scsBuilder["User ID"] = "name"; // @yourservername suffix sometimes.
this.scsBuilder["Password"] = "pwd";
this.scsBuilder["Database"] = "SQL_db";
I want to be sure that this.scsBuilder["Server"] = "tcp:abcdefghil.database.windows.net,1433";
keep FOREVER the same IP.
Thanks al lot, best regards
Hi Fabio,
Thank you for visiting the MSDN forum. I’m afraid that it is not the correct forum about this issue, since this forum is to discuss Visual C#. I am moving your question to the moderator
forum ("Where is the forum for..?"). The owner of the forum will direct you to a right forum. Thanks for your understanding.
Best regards,
Kristin
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.
Similar Messages
-
How to get the class name static method which exists in the parent class
Hi,
How to know the name of the class or reference to instance of the class with in the main/static method
in the below example
class AbstA
public static void main(String[] args)
System.out.println(getXXClass().getName());
public class A extends AbstA
public class B extends AbstA
on compile all the class and run of
java A
should print A as the name
java B
should print B as the name
Are there any suggestions to know the class name in the static method, which is in the parent class.
Regards,
Raja Nagendra KumarWell, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
The need we have is this
I have the test cases inheriting from common base class.
When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
I applicate your inputs on a better way to design without replicating the code..
In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
Regards,
Raja Nagendra Kumar
Edited by: rajanag on Jul 26, 2009 6:03 PM -
How to get the current class name in static method?
Hi,
I'd like to get the current class name in a static method. This class is intended to be extended. So I would expect that the subclass need not to override this method and at the runtime, the method can get the subclass name.
getClass() doesn't work, because it is not a static method.
I would suggest Java to make getClass() static. It makes sense.
But in the mean time, does anybody give an idea to work around it?
Thank you,
BillWhy not create an instance in a static method and use getClass() of the instance?
public class Test {
public static Class getClassName() {
return new Test().getClass(); -
Find the Class Name in a static method
Hi All,
I am trying to find the class name inside the static main method. I want to write one main method that loads an instance of the class. Other folks have suggested tricks with the security manager or creating an Exception to look at the stack trace, but these methods don�t reflect the inheritance. I want SUBCLASSES to be able to run from the command line using the inherited main method.
public static void main(String args[]){
JPanel thisJPanel = (JPanel) Class.forName(????).newInstance();
}Any IdeasI want
SUBCLASSES to be able to run from the command line
using the inherited main method.Someone pointed this out already but more directly, static methods are not inherited.
The behavior you desire ca be achieved using the Factory pattern.
The idea of being able to subclass an application is a little bizarre. Why don't you just do something like this:
public static void main(String[] args){
// check that there is at least one parameter
JPanel thisJPanel = (JPanel) Class.forName(args[0]).newInstance();
} -
Can we call a static method without mentioning the class name
public class Stuff {
public static final int MY_CONSTANT = 5;
public static int doStuff(int x){ return (x++)*x;}
import xcom.Stuff.*;
import java.lang.System.out;
class User {
public static void main(String[] args){
new User().go();
void go(){out.println(doStuff(MY_CONSTANT));}
}Will the above code compile?
can be call a static method without mentioning the class name?Yes, why do it simply?
pksingh79 wrote:
call a static method without mentioning the class name?For a given value of "without mentioning the class name".
public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
Class<?>[] types = new Class<?>[args.length];
for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args); -
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that
the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)(Microsoft SQL Server, Error: 2)
The system cannot find the file specified
Cannot connect to COWBOYS.
Here are the technical details===================================
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider:
Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (.Net SqlClient Data Provider)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=2&LinkId=20476
Error Number: 2
Severity: 20
State: 0
Program Location:
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer
timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance,
SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo ci, IServerType server)
at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()
===================================
The system cannot find the file specified
I have tried from so many forms. This is so frustrating. Thank for everyone/anyone who wants to help. So this is what happened: I had to uninstall my previous sqlserver 2012(which worked great) for some reason, and I uninstalled everything from that download.
Then I installed the trial edition of sql server 2012 (64 Bit) and It wouldn't connect to the database. (Error mentioned above.) My local DB is COWBOYS. (COWBOYS is also my computer name.) After this, I have tried downloading sqlexpress and sqlserver 64bit
many times and cannot connect to my local DB.
How do I connect to my Local DB?
Also, I think this might help: (When I run sqlserve.exe, which I was able to find in C:\Program Files\Microsoft SQL Server\110\LocalDB\Binn, I get an error: Your SQL server installation is either corrupt or has been tampered with(Error getting
instance ID from name). Please uninstall then re-run setup to correct this problem.
I would happily re install it, if it wasn't my 20th time.
I don't have any remote connections, I don't use username/password, only window authentication. I work mostly on visual studio, but without able to store /retrieve data, I don't know how to survive.
May be the solution is very simple, but I am too frustrated.
Some of the things I have tried:
From a command prompt, enter one of the following commands:
net start "SQL Server Agent (MSSQLSERVER)" OR
net start "SQL Server Agent(instancename)"(for instance)
on my sql configuration, I cannot start anything because there is nothing there to start. I can post more details, if that would help. Also, some more details about the error:
Details
Product:
SQL Server
ID:
2
Source:
MSSQLServer
Version:
10.0
Component:
SQLEngine
Message:
An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error:
40 - Could not open a connection to SQL Server) (.Net SqlClient Data Provider)
Explanation
SQL Server did not respond to the client request because the server is probably not started.
User Action
Make sure that the server is started.
Version:
9.0
Component:
SQLEngine
Message:
An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error:
40 - Could not open a connection to SQL Server) (.Net SqlClient Data Provider)
Explanation
SQL Server did not respond to the client request because the server is probably not started.
User Action
Make sure that the server is started.
Any one that can help me, I will be greatful. Thank you so much. p.s. please ask me anything if you have any questions.It sounds like there are a couple things going on here. First check if you have a successful install of SQL Server, then we'll figure out the connection issues.
Can you launch SQL Server Configuration Manager and check for SQL Server (MSSQLSERVER) if default instance or SQL Server (other name) if you've configured your instance as a named instance. Once you find this, make sure the service is started.
If not started, try to start it and see if it throws an error. If you get an error, post the error message your hitting. If the service starts, you can then launch SSMS and try to connect. If you have a default instance, you can use the machine
name in the connection dialog. Ex: "COWBOYS" where Cowboys is the machine name. However, if you named the SQL Server instance during install, you'll need to connect using the machine\instance format. Ex: COWBOYS\Romo (where Romo
is the instance name you set during install).
You can also look at the summary.txt file in the SQL Server setup error logs to see what happened on the most recent install. Past install history is archived in the log folder if you need to dig those up to help troubleshoot, but the most
recent one may help get to the bottom of it if there is an issue with setup detecting a prior instance that needs to be repaired.
Thanks,
Sam Lester (MSFT)
http://blogs.msdn.com/b/samlester
This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click
"Mark as Answer" and
"Vote as Helpful" on posts that help you. This can be beneficial to other community members reading the thread. -
Hi All,
I have written the code, for greater than (GJAHR) 2007 and restricted company codes ( table name = ZGLCCODE).
Here I have written the following the code which is giving an error
In "LOOP ... WHERE ..." the line type of the table must be statically defin
ZGLCCODE Contains only restricted company codes.
Code is as follows
TABLES : ZGLCCODE.
DATA : LT_DATAPACKAGE TYPE TABLE OF DTFIGL_4.
DATA : LS_PACKAGE TYPE DTFIGL_4.
TYPES: BEGIN OF LS_TZGLCCODE,
ZBUKRS type BUKRS,
END OF LS_TZGLCCODE.
DATA : LT_ITZGLCCODE TYPE LS_TZGLCCODE OCCURS 0 WITH HEADER LINE.
DATA : LI_NUM TYPE I,
LC_ZGJAHR TYPE BSEG-GJAHR VALUE '2007'.
SELECT ZBUKRS INTO TABLE LT_ITZGLCCODE FROM ZGLCCODE.
Note: "C_T_DATA" dynamic structure = "DTFIGL_4" structure
*- Remove from the DataSource Company Code -
LOOP AT C_T_DATA INTO LS_PACKAGE WHERE GJAHR GE '2007'.
READ TABLE LT_ITZGLCCODE WITH KEY ZBUKRS = LS_PACKAGE-BUKRS.
IF SY-SUBRC <> 0.
APPEND LS_PACKAGE TO LT_DATAPACKAGE.
ENDIF.
CLEAR LS_PACKAGE.
ENDLOOP.
IF LT_DATAPACKAGE[] IS NOT INITIAL.
DESCRIBE TABLE LT_DATAPACKAGE LINES LI_NUM.
IF LI_NUM GT 0.
REFRESH C_T_DATA.
APPEND LINES OF LT_DATAPACKAGE TO C_T_DATA.
REFRESH LT_DATAPACKAGE.
FREE LT_DATAPACKAGE.
endif.
ELSE.
REFRESH C_T_DATA.
ENDIF.
Please give me your valuable suggestions.
Thanks
Ganesh Reddy.Hi Ganesh,
whatever you do, you can try like this:
1 - any code posted should be wrapped in \
then try something like this:
field-symbols:
<tabrec> type any,
<field> type any.
sort ITZGLCCODE by bukrs.
LOOP AT C_T_DATA ASSIGNING <tabrec>.
ASSIGN component 'GJAHR' of structure <tabrec> to <field>.
check <field> <= 2007.
ASSIGN component 'BUKRS' of structure <tabrec> to <field>.
READ TABLE LT_ITZGLCCODE WITH KEY ZBUKRS = <field>
BINARY SEARCH TRANSPORTING NO FIELDS. "speed up the volume.
IF SY-SUBRC 0.
MOVE-CORRESPONDING <tabrec> to LS_PACKAGE.
APPEND LS_PACKAGE TO LT_DATAPACKAGE.
ENDIF.
ENDLOOP.
Regards,
Clemens -
How to pass the table name dynamically in xml parsing
Hi All,
I have created one procedure for parsing xml file which is working perfectly.
FORALL i IN t_tab.first .. t_tab.last
INSERT INTO Test_AP VALUES t_tab(i);Now I want to put the table name dynamically+. For that I have added one query and modify above code as follow:-
I have already declare dml_str varchar2(800) in declaration part.
Query is as follows:-
select table_name into tab_name from VERSION_DETAILS where SUBVERSION_NO=abc; -- here abc is variable name which contains values.
FORALL i IN t_tab.first .. t_tab.last
dml_str := 'INSERT INTO ' || tab_name || ' values :vals';
EXECUTE IMMEDIATE dml_str USING t_tab(i);But it's not working. How I will resolve this or through which way I achieved the intended results. Anyone can guide me on this matter.
Thanks in advance for your help...Hi,
But it's not working.Don't you think it would help to give the error message?
Put the assignment before FORALL.
FORALL only accepts one subsequent DML statement (static or dynamic SQL) :
dml_str := 'INSERT INTO ' || tab_name || ' values :vals';
FORALL i IN t_tab.first .. t_tab.last
EXECUTE IMMEDIATE dml_str USING t_tab(i); -
Need to know the column names in my dynamic select clause
Dear All,
Please go through the following code. While executing the following code i am getting an error saying that dbms_sql.describe_columns overflow, col_name_len=35. Use describe_columns2.
Please guide me how to proceed further. Or please help me, how can i get the column names when i issue a dynamic select clause.
DECLARE
CUR INTEGER;
COL_CNT INTEGER ;
A INTEGER;
SEL_CLAUSE VARCHAR2(2000);
DESC_T DBMS_SQL.DESC_TAB;
REC DBMS_SQL.DESC_REC;
b number;
BEGIN
SEL_CLAUSE := 'SELECT 1,2,DECODE(1,1,''ONE'',2,''TWO'',3,''THREE'') FROM DUAL';
--'SELECT ROWID,PARA_SUB_CODE,DECODE('||''''||'ENG'||''''||','||''''||'ENG'||''''||',PARA_NAME,PARA_BL_NAME),NULL,NULL FROM PCOM_APP_PARAMETER';
--'SELECT 1,2,DECODE(1,1,''ONE'',2,''TWO'') FROM DUAL';
DBMS_OUTPUT.PUT_LINE( SEL_CLAUSE );
CUR := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(CUR,SEL_CLAUSE,DBMS_SQL.NATIVE);
DBMS_SQL.DESCRIBE_COLUMNS(CUR,COL_CNT,DESC_T);
B := desc_t.first;
FOR J IN 1..COL_CNT
LOOP
DBMS_OUTPUT.PUT_LINE('J := '||J || ' COL CNT ' || COL_CNT);
END LOOP;
BEGIN
A := DBMS_SQL.EXECUTE(CUR);
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
END;
Regards,
BalajiIs there any way can i have it directly??It does not work with static SQL either. Dynamic SQL is no different.
SQL> select 1 x from dual where x = 1 ;
select 1 x from dual where x = 1
ERROR at line 1:
ORA-00904: "X": invalid identifier
SQL>As suggested already, you will need to use alias if you want your select expression to be referred in the where clause.
SQL> BEGIN
2 FOR rec IN (SELECT *
3 FROM (SELECT 1,
4 2,
5 DECODE(1, 1, 'ONE', 2, 'TWO', 3, 'THREE') "DECODE(1, 1, 'ONE', 2, 'TWO', "
6 FROM DUAL)
7 WHERE "DECODE(1, 1, 'ONE', 2, 'TWO', " = 'ONE')
8 LOOP
9 NULL;
10 END LOOP;
11 END;
12 /
PL/SQL procedure successfully completed.
SQL>Message was edited by:
Kamal Kishore -
I'm running the DNS server role on Windows Server 2012 R2 on a physical machine on my home network.
My AD is configured with a non-registered name - let's say it's "home.acme.ca" and the DNS server is configured to host that zone. I also configured a 2nd zone in the DNS server called "myinf.acme.ca". They both run on a physical
server with an IP of 192.168.1.10
The DHCP server on my Cable Modem is configured to hand out 192.168.1.10 as the only DNS server to every device on my network. On my servers (with static IP addresses), 192.168.1.10 is configured as the only DNS server available for them.
I took the DNS servers from my Cable Provider and configured a Forwarder on my server to send name resolution requests to them only if my DNS server can not answer the request - basically for any name resolution request that does not end with ".home.acme.ca"
or ".myinf.acme.ca"
The "home.acme.ca" zone is populated with 'A' records for all of the physical and virtual servers and PC's on my network.
The "myfin.acme.ca" zone is populated with 'CNAME' records that point directly to the 'A' record in "home.acme.ca" - for example, I have a serve named s000abc123ww.home.acme.ca with an 'A' record providing an IP address of 192.168.1.20 and
I created a 'CNAME' (alias) record named 'webserver.myinf.acme.ca' which points to the 'A' record 's000abc123ww.home.acme.ca'
2 of my 6 machines can resolve the alias but not the real name of the server!
.10 is the Domain Controller. All of the other machines (except .98) are members of the home.acme.ca domain.
I attempted to ping 's000abc123ww.home.acme.ca' AND 'webserver.myinf.acme.ca' on the following 6 computers. I used the fully qualified name in all cases.
4 of the below machines are able to resolve BOTH names. The other 2 can resolve the Alias but not the real name!
I don't understand how this is possible, but I would like to fix it...!!! Please help?
.10 - Server 2012 R2 (Physical) - Hosts Active Directory and DNS.
.20 - Server 2012 R2 (Virtual) - Runs SQL Server
.21 - Server 2012 R2 (Virtual) - Runs Apache
.22 - Server 2012 R2 (Virtual) - Runs Apache. This is the device I am trying to ping (s000abc123ww)
.98 - Windows 7 (Physical)
.99 - Windows 7 (Virtual)
.21 (which is configured nearly identically to .20 and .22) can resolve and ping the Alias, but not the real name.
.98 can also resolve and ping the Alias, but not the real name.
The rest of the machines can resolve and ping both the alias and the real name.
All of the Virtual Machines are running under Hyper-V on the .10 physical server.
All the devices are on the same subnet.
Thank in advance to anyone who can help me understand and correct this problem!
JimHi,
CNAME resource records are recommended for use in the following scenarios:
• When a host that is specified in an A resource record in the
same zone needs to be renamed
• When a generic name for a well-known server, such as www, must resolve to a group of individual computers (each with individual A resource records) that provide the same
service, for example, a group of redundant Web servers
Therefore please try to create your CNNAM record in the same zone and try again.
The related KB:
Adding, Changing, and Deleting Resource Records
http://technet.microsoft.com/en-us/library/cc779020(v=ws.10).aspx
Hope this helps.
We
are trying to better understand customer views on social support experience, so your participation in this
interview project would be greatly appreciated if you have time.
Thanks for helping make community forums a great place. -
Getting the table names in an MS Access database
Hi,
I am new to JDBC and making a client/server application that updates a MS Access database through jdbc:odbc.
I need to get a list of existing user tables in the db. I have found a great document on the net which has the code, however the code doesn't work. I have tried different ways and looked every where with no success. (link to the doco: http://www-128.ibm.com/developerworks/opensource/library/j-jdbc-objects/)
Here is my dbManager class that handles all db related services in my application. I would appreciate any help I can get as I have exhusted all my avenues.
Thanks
Sep,
* dbManager.java
* Created on 31 October 2005, 10:20
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
import java.io.*;
import java.sql.*;
import java.util.regex.*;
* @author AUMahdavSe
public class dbManager {
/** Constant Declaration */
public static final String Driver = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final
String sqlCreateTable = "create table TABLENAME (" +
"name varchar (100)," +
"surname varchar(100)," +
"computerType integer," +
"computerNAL varchar(20)," +
"haveMonitor integer," +
"monitorNAL varchar (20)," +
"auditDate varchar(10) );";
public static final String sqlUpdateTable = "insert into TABLENAME values" +
" (NAMEHOLDER, SURNAMEHOLDER, COMPTYPE, COMPNAL, HAVEMON, MONNAL);";
/** Attributes */
private String dbURL = "jdbc:odbc:";
private String Username = "admin"; // user input
private String Password = "purina123"; // user input
private String ODBCDataSource; // config file
private String dbPath; // set through config file or defaults to current folder
private String configFile = "config.txt"; // set either at commandline or defaults to current folder
private Connection con = null;
private Statement stmt = null;
private ResultSet tables;
private DatabaseMetaData dma;
private ResultSetMetaData rsmd;
private String CurrentAuditTable = "TestTable2";
int numCols, i;
/** Set Methodes */
public void setUsername( String usr ) {
this.Username = usr;
public void setPassword( String pswd ) {
this.Password = pswd;
public void setDbPath( String path ) {
this.dbPath = path;
public void setODBCDataSource( String ds ) {
this.ODBCDataSource = ds;
public void setDbURL( String dsname ) {
this.dbURL = this.dbURL + dsname;
/** Get Methodes */
public String getDriver() {
return this.Driver;
// can be run only after a connection obj is setup
public void getMDA() {
try {
this.dma = this.con.getMetaData();
catch (SQLException ex) {
System.err.println("database connection: " + ex.getMessage());
public void getDBTables() {
//now dump out the names of the tables in the database
String[] types = new String[1];
types[0] = "TABLES"; //set table type mask
//note the %-sign is a wild card (not '*')
try {
this.tables = this.dma.getTables(null, null, "%", types);
dumpResults("--Tables--");
this.tables.close();
//this.listTables();
catch (SQLException ex) {
System.err.println("database connection: " + ex.getMessage());
// listing tables
/*int count = 0;
int numCols = 0;
//ResultSetMetaData rsmd;
try {
System.out.println("Listing db tables ...");
//this.tables.beforeFirst();
rsmd = this.tables.getMetaData();
numCols = rsmd.getColumnCount();
System.out.println("number of cols: " + numCols);
boolean more = this.tables.first();
System.out.println("this is why: " + more);
while ( more ) {
count++;
for (int i = 1; i <= numCols; i++)
System.out.print( "Table-" + count + " -> " + this.tables.getString(count)+" " );
System.out.println();
more = this.tables.next();
catch ( SQLException ex ) {
System.out.println( "problem listing db tables: " + ex.getMessage() );
/** Other Methodes */
// Initialize the db parameters, like driver, username, passwd, etc.
public void dbInitialize() {
// load configuration from config.txt (dbPath and ODBC Data Source name)
this.loadDbConfig();
// loadDriver
this.loadDriver();
// get username and password for the ODBC from user
this.getDSSecurity();
// populate dbURL, username and password
this.setDbURL( this.ODBCDataSource );
// connect to db
this.dbConnect();
// get db metadata
this.getMDA();
// get a list of tables in db
this.getDBTables();
// load JDBC driver
public void loadDriver() {
try {
Class.forName( getDriver() );
} catch (Exception e) {
System.out.println("Failed to load JDBC/ODBC driver.");
return;
// connects to db and create a Connection obj and a Statement obj
public void dbConnect() {
try {
this.con = DriverManager.getConnection (
this.dbURL,
this.Username,
this.Password);
this.stmt = con.createStatement();
} catch (Exception e) {
System.err.println("problems connecting to "+this.dbURL);
// creates table tblname in db
public void CreateTable( String tblname ) {
try {
String sqlcommand = mergeTblName(sqlCreateTable, tblname);
this.stmt.execute( sqlcommand );
catch (SQLException ex) {
System.err.println("problems with SQL statement sent to "+this.dbURL+
": "+ex.getMessage());
System.out.println("SQL Command: " + mergeTblName(sqlCreateTable, tblname) );
// updates db with new record(s) by executing the SQL query sqlstmt
// and closes db connection
public void dbUpdate( String sqlstmt ) {
try {
// execute SQL commands to create table, insert data
this.stmt.execute( sqlstmt );
this.con.close();
} catch (Exception e) {
System.err.println("problems with SQL sent to "+this.dbURL+
": "+e.getMessage());
// list all user tables in the db
public void listTables() {
//now dump out the names of the tables in the database
int count = 0;
try {
System.out.println("Listing db tables ...");
//this.tables.beforeFirst();
while ( this.tables.next() ) {
count++;
System.out.print( "Table-" + count + " -> " + this.tables.getString(1) );
System.out.println();
catch ( SQLException ex ) {
System.out.println( "problem listing db tables: " + ex.getMessage() );
// checks whether tbname exist in db as a table
// this function has to be called after dbConnect
public boolean tableExists( String tbname ) {
boolean tbexists = false;
//get the database metadata
try {
dma = con.getMetaData();
catch (SQLException ex) {
System.err.println("database connection: " + ex.getMessage());
//now dump out the names of the tables in the database
String[] types = new String[1];
types[0] = "TABLES"; //set table type mask
//note the %-sign is a wild card (not '*')
try {
tables = dma.getTables(null, null, "%", types);
catch (SQLException ex) {
System.err.println("database connection: " + ex.getMessage());
try {
while ( tables.next() ) {
if ( tbname.equalsIgnoreCase( tables.getString(1) ) ) {
tbexists = true;
catch ( SQLException ex ) {
System.err.println("database connection: " + ex.getMessage());
return tbexists;
// merge tablename using REGEX
public String mergeTblName( String sqlcommand, String tbname ) {
String REGEX = "TABLENAME";
String INPUT = sqlcommand;
String REPLACE = tbname;
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
INPUT = m.replaceAll(REPLACE);
//System.out.println(INPUT);
return INPUT;
// merge feildnames specific terms using REGEX
public String mergeFldName( Message msg ) {
String sqlcommand;
sqlcommand = "insert into TABLENAME values" +
" ('" + msg.getName() + "', '" + msg.getSurname() + "', " +
msg.getComputerType() + ", '" + msg.getComputerNAL() + "', " +
msg.getHaveMonitor() + ", '" + msg.getMonitorNAL() + "', '" +
msg.getDateOfMsg() + "');";
sqlcommand = mergeTblName( sqlcommand, CurrentAuditTable );
return sqlcommand;
// get users input char
/**public char getChar() {
int i = System.in.read();
while (i != -1) {
// here's your character
char c = (char) i;
i = System.in.read();
return (char) i;
// load the config parameters from config.txt
public void loadDbConfig() {
// make a file obj pointing to the config file config.txt
File configFile = new File( this.configFile );
//...checks on configFile are elided
StringBuffer contents = new StringBuffer();
//declared here only to make visible to finally clause
BufferedReader input = null;
try {
//use buffering
//this implementation reads one line at a time
input = new BufferedReader( new FileReader(configFile) );
String line = null; //not declared within while loop
int count = 0;
while (( line = input.readLine()) != null){
//first line in config file is dbPath
if(count == 0) this.setDbPath( line.trim() );
//second line in config file is ODBCDataSource
if(count == 1) this.setODBCDataSource( line.trim() );
count++;
//contents.append(line);
//contents.append(System.getProperty("line.separator"));
catch (FileNotFoundException ex) {
System.err.println("the file congif.txt cannot be found ...");
System.err.print("Enter the path to db file (e.g. c:\\temp): ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the db path from the command-line; need to use try/catch with the
// readLine() method
try {
this.setDbPath( br.readLine() );
catch (IOException ioe) {
System.out.println("IO error trying to read user input.");
System.exit(1);
System.err.print("Enter the name of the ODBC Data Source: ");
// read the ODBC Data Source name from the command-line; need to use try/catch with the
// readLine() method
try {
this.setODBCDataSource( br.readLine() );
catch (IOException ioe) {
System.out.println("IO error trying to read user input.");
System.exit(1);
ex.printStackTrace();
catch (IOException ex){
//ex.printStackTrace();
finally {
try {
if (input!= null) {
//flush and close both "input" and its underlying FileReader
input.close();
catch (IOException ex) {
//ex.printStackTrace();
//return contents.toString();
// get datasource security details i.e. username and password
public void getDSSecurity() {
// get username
System.out.print("Enter username for the ODBC DataSource: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
this.setUsername( br.readLine() );
catch (IOException ioe) {
System.out.println("IO error trying to read username.");
System.exit(1);
// get password
System.out.print("Enter password: ");
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
this.setPassword( br.readLine() );
catch (IOException ioe) {
System.out.println("IO error trying to read password.");
System.exit(1);
private void dumpResults(String head)
//this is a general routine to print out
//column headers and the contents of each column
System.out.println(head);
try
//get the number of columns from the metadata
this.rsmd = this.tables.getMetaData();
numCols = this.rsmd.getColumnCount();
//print out the column names
for (i = 1; i<= numCols; i++)
System.out.print(rsmd.getColumnName(i)+" ");
System.out.println();
//print out the column contents
boolean more = this.tables.next();
while (more)
for (i = 1; i <= numCols; i++)
System.out.print(this.tables.getString(i)+" ");
System.out.println();
more = this.tables.next();
catch(Exception e)
{System.out.println(e.getMessage());}
/** Creates a new instance of dbManager */
public dbManager() {
this.dbInitialize();
}here is the result when I make a new dbManager obj from my server class which is a multithreaded one.
H:\java>java EchoServer
Enter username for the ODBC DataSource: admin
Enter password: purina123
Tables
TABLE_CAT TABLE_SCHEM TABLE_NAME TABLE_TYPE REMARKS
Listening for clients on 12111...
here is the code of my server class called EchoServer:
import java.net.*;
import java.io.*;
public class EchoServer
ServerSocket m_ServerSocket;
dbManager haDB;
public EchoServer()
// db methods to setup a jdbc connection to the database
haDB = new dbManager();
// list tables
//haDB.listTables();
//haDB.getDBTables();
// create table
//haDB.CreateTable("TestTable2");
// update table
// server code
try
// Create the server socket.
m_ServerSocket = new ServerSocket(12111);
catch(IOException ioe)
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
System.out.println("Listening for clients on 12111...");
// Successfully created Server Socket. Now wait for connections.
int id = 0;
while(true)
try
// Accept incoming connections.
Socket clientSocket = m_ServerSocket.accept();
// accept() will block until a client connects to the server.
// If execution reaches this point, then it means that a client
// socket has been accepted.
// For each client, we will start a service thread to
// service the client requests. This is to demonstrate a
// multithreaded server, although not required for such a
// trivial application. Starting a thread also lets our
// EchoServer accept multiple connections simultaneously.
// Start a service thread
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++, haDB);
cliThread.start();
catch(IOException ioe)
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
public static void main (String[] args)
new EchoServer();
class ClientServiceThread extends Thread
Socket m_clientSocket;
int m_clientID = -1;
dbManager m_db;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int clientID, dbManager db)
m_clientSocket = s;
m_clientID = clientID;
m_db = db;
public void run()
// Obtain the input stream and the output stream for the socket
// A good practice is to encapsulate them with a BufferedReader
// and a PrintWriter as shown below.
BufferedReader in = null;
PrintWriter out = null;
Message msg = new Message();
// Print out details of this connection
System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " +
m_clientSocket.getInetAddress().getHostName());
try
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
// At this point, we can read for input and reply with appropriate output.
// Run in a loop until m_bRunThread is set to false
while(m_bRunThread)
// read incoming stream
String clientCommand = in.readLine();
if ( clientCommand.indexOf(",") != -1 ) {
msg.deserialize( clientCommand );
System.out.println("SQL command: " + m_db.mergeFldName(msg) );
m_db.dbUpdate( m_db.mergeFldName(msg) );
//System.out.println("Name :" + msg.getName() );
//System.out.println("Surname :" + msg.getSurname() );
//System.out.println("ComputerType :" + msg.getComputerType() );
//System.out.println("ComputerNAL :" + msg.getComputerNAL() );
//System.out.println("HaveMonitor :" + msg.getHaveMonitor() );
//System.out.println("Monitor NAL :" + msg.getMonitorNAL() );
//System.out.println("AuditDate :" + msg.getDateOfMsg() );
System.out.println("Client Says :" + clientCommand);
if(clientCommand.equalsIgnoreCase("quit"))
// Special command. Quit this thread
m_bRunThread = false;
System.out.print("Stopping client thread for client : " + m_clientID);
else
// Echo it back to the client.
out.println(clientCommand);
out.flush();
catch(Exception e)
e.printStackTrace();
finally
// Clean up
try
in.close();
out.close();
m_clientSocket.close();
System.out.println("...Stopped");
catch(IOException ioe)
ioe.printStackTrace();
}I find that taking any problem and reducing it to the simplest thing is the best way to approach it.
Why you had to post all that bloody code (especially since you didn't write it) is beyond me.
This will list all the tables in an Access database (or any other, for that matter):
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
public class TableLister
public static final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final String DATABASE = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
public static final String USERNAME = "admin";
public static final String PASSWORD = "";
public static void main(String [] args)
try
String driver = ((args.length > 0) ? args[0] : DRIVER);
String url = ((args.length > 1) ? args[1] : DATABASE);
String username = ((args.length > 2) ? args[2] : USERNAME);
String password = ((args.length > 3) ? args[3] : PASSWORD);
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
DatabaseMetaData meta = conn.getMetaData();
// Bring back ALL tables and views, including SYSTEM tables.
ResultSet tables = meta.getTables(null, null, null, null);
ResultSetMetaData rsmd = tables.getMetaData();
int numColumns = rsmd.getColumnCount();
List columnNames = new ArrayList();
for (int j = 0; j < numColumns; ++j)
columnNames.add(rsmd.getColumnName(j+1));
Element root = new Element("tables");
int tableCount = 0;
while (tables.next())
Element table = new Element("table");
table.setAttribute("id", Integer.toString(++tableCount));
for (int j = 0; j < numColumns; ++j)
Element column = new Element((String)columnNames.get(j));
column.setText(tables.getString((String)columnNames.get(j)));
table.addContent(column);
root.addContent(table);
conn.close();
Document doc = new Document(root);
XMLOutputter outputter = new XMLOutputter(" ", true);
System.out.println(outputter.outputString(doc));
catch (ClassNotFoundException e)
System.err.println("Couldn't load JDBC driver class");
e.printStackTrace();
catch (SQLException e)
System.err.println("SQL state: " + e.getSQLState());
System.err.println("SQL error: " + e.getErrorCode());
e.printStackTrace();
catch (Exception e)
e.printStackTrace();
}Run it and see if it works for you. If it does, put the essence of the code into your stuff.
% -
hi ,
when generate the schema , i got the below error, please any one put your inputs:
Connecting to the LOB system has failed. A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server
is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).thaks shanky,
but facing another , after generate schema from WCF_SQL, im unable get elements in my schema.
this is schema generate from storeprocduer , but thru WCF-sql im unable get the elements like
id, name
<xsd:schema targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet2" xmlns:schema="urn:schemas-microsoft-com:sql:SqlRowSet2" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:sqltypes="http://schemas.microsoft.com/sqlserver/2004/sqltypes" elementFormDefault="qualified">
<xsd:import namespace="http://schemas.microsoft.com/sqlserver/2004/sqltypes" schemaLocation="http://schemas.microsoft.com/sqlserver/2004/sqltypes/sqltypes.xsd" />
<xsd:element name="Test.dbo.sample">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="sqltypes:int" minOccurs="0" />
<xsd:element name="name" minOccurs="0">
<xsd:simpleType>
<xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions="IgnoreCase IgnoreKanaType IgnoreWidth" sqltypes:sqlSortId="52">
<xsd:maxLength value="1000" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<Test.dbo.sample xmlns="urn:schemas-microsoft-com:sql:SqlRowSet2">
<id>18</id>
<name>BIRADAR</name>
</Test.dbo.sample>
<Test.dbo.sample xmlns="urn:schemas-microsoft-com:sql:SqlRowSet2">
<id>18</id>
<name>BIRADAR</name>
</Test.dbo.sample>
<Test.dbo.sample xmlns="urn:schemas-microsoft-com:sql:SqlRowSet2">
<id>19</id>
<name>sw</name>
</Test.dbo.sample>
<Test.dbo.sample xmlns="urn:schemas-microsoft-com:sql:SqlRowSet2">
<id>18</id>
<name>BIRADAR</name>
</Test.dbo.sample>
<Test.dbo.sample xmlns="urn:schemas-microsoft-com:sql:SqlRowSet2">
<id>14</id>
<name>swe</name>
</Test.dbo.sample>
<Test.dbo.sample xmlns="urn:schemas-microsoft-com:sql:SqlRowSet2">
<id>13</id>
<name>se</name>
</Test.dbo.sample> -
How to get the full path instead of just the file name, in �FileChooser� ?
In the FileChooserDemo example :
In the statement : log.append("Saving: " + file.getName() + "." + newline);
�file.getName()� returns the �file name�.
My question is : How to get the full path instead of just the file name,
e.g. C:/xdirectory/ydirectory/abc.gif instead of just abc.gif
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
public class FileChooserDemo extends JFrame {
static private final String newline = "\n";
public FileChooserDemo() {
super("FileChooserDemo");
//Create the log first, because the action listeners
//need to refer to it.
final JTextArea log = new JTextArea(5,20);
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
//Create a file chooser
final JFileChooser fc = new JFileChooser();
//Create the open button
ImageIcon openIcon = new ImageIcon("images/open.gif");
JButton openButton = new JButton("Open a File...", openIcon);
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//this is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
} else {
log.append("Open command cancelled by user." + newline);
//Create the save button
ImageIcon saveIcon = new ImageIcon("images/save.gif");
JButton saveButton = new JButton("Save a File...", saveIcon);
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showSaveDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//this is where a real application would save the file.
log.append("Saving: " + file.getName() + "." + newline);
} else {
log.append("Save command cancelled by user." + newline);
//For layout purposes, put the buttons in a separate panel
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
//Explicitly set the focus sequence.
openButton.setNextFocusableComponent(saveButton);
saveButton.setNextFocusableComponent(openButton);
//Add the buttons and the log to the frame
Container contentPane = getContentPane();
contentPane.add(buttonPanel, BorderLayout.NORTH);
contentPane.add(logScrollPane, BorderLayout.CENTER);
public static void main(String[] args) {
JFrame frame = new FileChooserDemo();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.pack();
frame.setVisible(true);simply use file.getPath()
That should do it!Thank you !
It takes care of the problem !! -
Get the pc name with domain name and add it to my properties file using commands
i want to get the pc name with domain name and add it to my properties file using powershell .
sidfunction Get-Environment{
[environment]|Get-Member -Static -MemberType Properties |
ForEach-Object{
if($_.Name -ne 'StackTrace'){
$v=[scriptblock]::Create("[environment]::$($_.Name)").Invoke()
New-Object PsCustomObject -Property ([ordered]@{Name=$_.Name;Value=$v[0]})
Get-Environment
Get-Environment | Out-String | Out-File environment.txt
¯\_(ツ)_/¯ -
How to get the initial name.
public class asd{
public static void main(String[] args){
asd dkd =new asd();
how to show the object's name(dkd)?Are you trying to obtain the reference variable name is?
Here is an example:
String str = new String("God is real!"); // "str" would be the reference variable nameIf you call the toString() method you will won't get "str". You would get "God is real!". Look at my example below:
String str = new String("God is real!"); // "str" would be the reference variable name
System.out.println(str.toString());OUTPUT:
"God is real!"
If you do a to string on like this:
asd dkd = new asd();
System.out.println(dkd.toString()); The Output would look like this:
"asd@lfee6fc"
I'm not clear on what you mean by object name, but using the toString() method wouldn't be how I would get it. If you mean the Class name you could use the getClass().toString() methods to obtain the Class name. That would give you "java.lang.String" for the first example and the second ouputput would be "class asd".
Maybe you are looking for
-
Windows keeps on asking for my user credentials
Hi. As per subject, I keep on getting prompted to enter my user credentials whenever I open a mapped drive (which has been mapped before with the same credentials) or when I open the SharePoint site and also when I check out and edit a document from
-
I'm running JSPs and servlets under Netscape (Tomcat) web server and am getting errors with my jsp file's first line: [%@page import="java.util.*, myclass" %] Netscape server throws an error saying that it can't import myclass. I've put the myclass.c
-
hi I am having a doubt in Idoc in creating Model view. I had made a Z-segment,infotype,message type & in WE82 had assigned the infotype to message type. But when i m craeting am model view I am trying to add ths z message type to model view,its not s
-
I have editable regions that I have removed in my templates but they are still present in the pages that were created from the templates how can I remove them in the pages??,
-
Calling oracle command window through forms
I need to call oracle command window in the forms. in the sence when i clicked a button in forms then oracle window has to open. Is that possible to call a oracle command window in forms. Please help me in this. Thanks in advance, raju.