I work with sql server as database in Java NetBeans and I want to create a database from Java, before doing this I need to check if it exists or not, I know that the sql syntax is large different from MySQL syntax so at the begining I did this sql syntax:
CREATE DATABASE IF NOT EXISTS
But it returns error so please can you tell how to check if it exist in this case it will not be created and if not exists how to create one. THANK YOU
One more way is to use DB_ID:
IF DB_ID(N'YourDBName') IS NULL
CREATE DATABASE YourDBName ....;
Returns the database identification (ID) number.
try {
String sql = "SELECT * FROM master.dbo.sysdatabases WHERE name = '"+base+"'";
pstt=conn.prepareStatement(sql);
rs = pstt.executeQuery();
if (rs.next()){
System.out.println("Database exist");
}
else{
String sqll = "CREATE DATABASE "+base;
pstt=conn.prepareStatement(sqll);
pstt.executeUpdate();
}
}
catch(Exception e){
}
i've tried this and it works fine with me, any way thanks for your reply
Related
Sorry for posting this even though there're a few posts about this , but they're not helping.
I'm using sqlite with QT , I wanted to do a simple query but it gives me this error:
file is encrypted or is not a database Unable to execute statement
Some posts' comments say that the DB may be corrupt, I used another program and created a test table from scratch and still has the same problem, this is the code:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("AdmissionTestDB.sql");
db.open();
if(db.isOpen())
{
QSqlQuery q = db.exec("SELECT * FROM USERS");
if(!q.lastError().isValid())
{
qDebug()<<"works!";
while(q.next())
{
qDebug()<<q.value(8).toString();
}
}
else
qDebug()<<"---db failed to open! , error: "<<q.lastError().text();
db.close();
return true;
}
qDebug()<<"db failed to open! , error: "<<db.lastError().text();
return false;
More Information hopefully it would help solving this:
1- I'm using SQLITE 3
2- The problem happens when I use QSqlQuery q = db.exec("SELECT * FROM USERS"); so the DB actually opens!
3- I used two GUI programs to create the DB one of them is the latest version of SQLiteStudio which is version 3.0.4
I am using Hibernate to access my database. I would like to delete a set of fields on function of a criteria. My database is PostgreSQL and my Java code is:
public void deleteAttr(String parameter){
Configuration cfg = new Configuration();
cfg.configure(resource.getString("hibernate_config_file"));
SessionFactory sessionFactory = cfg.buildSessionFactory();
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
tx.begin();
String sql = "delete from attribute where timestamp > to_date('"+parameter+"','YYYY-MM-DD')"
session.createSQLQuery(sql);
tx.commit();
}
The method runs, but it doesn't delete data from database. I have also checked the sql sentence in PgAdmin and it works, but not in code. Why? Does someone help me?
Thanks in advance!
It's because you're creating a query, but you don't execute it:
String sql = "delete from attribute where timestamp > to_date('"+parameter+"','YYYY-MM-DD')"
Query query = session.createSQLQuery(sql);
query.executeUpdate();
You should really use bound named parameters rather than string concatenation to pass parameters in your query: it's usually more efficient, it' much more robust, but above all, it doesn't open the door to SQL injection attacks.
In my app the users gets to pick from a list of SQL Server in the network. The thing is I need to know if the chosen instance is a local or remote computer.
Is there a way I can ask that SQL instance what computer is she on? Is there a way a can figure that out?
Edit1: I want to know the host name where the SQL Server is hosted so I can then compare that to System.Environment.MachineName and know for sure is that Sql Server is running on the same machine where my app is running
Edit2: ##servername returned my computername\sqlinstance while SELECT SERVERPROPERTY('MachineName') returns just the computername, which is exactly what I want
Use ##Servername, for example:
SELECT ##servername
Alternately you could do this
SELECT SERVERPROPERTY('MachineName')
From MSDN on the differences between these approaches:
The ServerName property of the
SERVERPROPERTY function and
##SERVERNAME return similar
information. The ServerName property
provides the Windows server and
instance name that together make up
the unique server instance.
##SERVERNAME provides the currently
configured local server name.
The ServerName property and
##SERVERNAME return the same
information if the default server name
at the time of installation has not
been changed.
If the local server name has been
changed from the default server name
at installation time, ##SERVERNAME
returns the new name.
Do you actually have login permissions on all the instance(s) of SQL Server? If so you could execute sp_helpserver or ##servername and compare the name returned with Environment.MachineName.
If you don't have login access, you can write a small C# console program to return the server name of every SQL Server instance on the local network:
using System;
using System.Data.Sql;
class Program
{
static void Main()
{
// Retrieve the enumerator instance and then the data.
SqlDataSourceEnumerator instance =
SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
// Display the contents of the table.
// The first column is the server name.
DisplayData(table);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static void DisplayData(System.Data.DataTable table)
{
foreach ( System.Data.DataRow row in table.Rows )
{
foreach ( System.Data.DataColumn col in table.Columns )
{
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
}
Console.WriteLine("============================");
}
}
}
sp_who2 returns the hostname
To use Filestream on a DB 3 steps must be done:
1) enable it a server/instance level
2) enable it (sp_configure) at DB level
3) create a varbinary(max) field that supports filestream
(2) and (3) are done easily with T-SQL
(1) is doable manually from SQL Server Configuration Manager, basically what I need is to check all the 3 checkboxes:
(source: sql-server-performance.com)
but how is it possible to automize it?
I found this artcile "Enabling filestream usin a VBScript", is there another way to do it than using VBScripts? May be something that is possible to do only with 2008R2?
In case it VBScript is the only solution, which are the possible downsides?
The only way other than clicking in the Configuration Manager is via WMI (which is what the VBScript does). If you don't like VB, here's how I've been configuring it from C# (note that the code needs to run with admin privileges (elevated)):
private ManagementObject GetFilestreamManagementObject(string machineName, string instanceName)
{
string managementPath = string.Format(#"\\{0}\root\Microsoft\SqlServer\ComputerManagement10", machineName);
ManagementScope managementScope = new ManagementScope(managementPath);
managementScope.Connect();
SelectQuery query = new SelectQuery("FilestreamSettings", string.Format("InstanceName='{0}'", instanceName));
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(managementScope, query))
{
ManagementObjectCollection moc = searcher.Get();
if (1 != moc.Count)
{
string exceptionText = String.Format("Expected single instance of FilestreamSettings WMI object, found {0}.", moc.Count);
throw new FilestreamConfigurationException(exceptionText);
}
ManagementObjectCollection.ManagementObjectEnumerator enumerator = moc.GetEnumerator();
if (false == enumerator.MoveNext())
{
throw new FilestreamConfigurationException("Couldn't move ManagementObjectEnumerator to the first entry.");
}
return (ManagementObject)enumerator.Current;
}
}
private void EnableFilestream(int accessLevel)
{
ManagementObject filestreamSettingsObject = GetFilestreamManagementObject("myMachine", "MSSQLSERVER");
ManagementBaseObject methodArgs = filestreamSettingsObject.GetMethodParameters("EnableFilestream");
methodArgs["AccessLevel"] = accessLevel;
methodArgs["ShareName"] = ""; //default
ManagementBaseObject returnObject = filestreamSettingsObject.InvokeMethod("EnableFilestream", methodArgs, null);
if (returnObject == null)
{
throw new FilestreamConfigurationException("Result of calling filestreamSettingsObject.InvokeMethod(\"EnableFilestream\", methodArgs, null)" is null);
}
uint returnValue = (uint)returnObject.GetPropertyValue("ReturnValue");
const uint errorSuccessRestartRequired = 0x80070BC3;
if (returnValue != 0 && returnValue != errorSuccessRestartRequired)
{
Win32Exception win32Exception = new Win32Exception((int)returnValue);
string exceptionText =
string.Format("'EnableFilestream' method returned {0}: {1}", returnValue, win32Exception.Message);
throw new FilestreamConfigurationException(exceptionText);
}
}
Just run this.
USE master
Go
EXEC sp_configure 'show advanced options'
GO
EXEC sp_configure filestream_access_level, 3
GO
EXEC sp_filestream_configure
#enable_level = 3
, #share_name = N'FS';
GO
RECONFIGURE WITH OVERRIDE
GO
More on this
http://www.mssqltips.com/tip.asp?tip=1489
0 = disabled (this is the default)
1 = enabled only for T-SQL access
2 = enabled for T-SQL access and local
file system access
3 = enabled for T-SQL access, local
file system access, and remote file
system access
You can store the script in a stored procedure and call it from your application or anywhere you want.
Here're links on this topic
http://www.mssqltips.com/tip.asp?tip=1838
Link
http://technet.microsoft.com/en-us/library/cc645923.aspx
http://www.sql-server-performance.com/articles/dba/Configure_Filestream_in_SQL_Server_2008_p1.aspx
EDIT
Answer to your comment.
Here's what I call step 2
CREATE DATABASE Archive
ON
PRIMARY ( NAME = Arch1,
FILENAME = 'c:\data\archdat1.mdf'),
FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM( NAME = Arch3,
FILENAME = 'c:\data\filestream1')
LOG ON ( NAME = Archlog1,
FILENAME = 'c:\data\archlog1.ldf')
GO
http://technet.microsoft.com/en-us/library/cc645585.aspx
Check link for all steps
Filestream in Sql Server 2008 Express
Good Luck!
Pawel's solution worked great for us. We were seeing about a 50% failure rate using the VBS -- haven't seen a failure yet with Pawel's approach. Unlike Greg's results, it has worked great for us against a local system. Actually, that's all we have tried it with.
We did have to make a couple of adjustments to Pawel's code. The line
throw new FilestreamConfigurationException("Result of calling filestreamSettingsObject.InvokeMethod(\"EnableFilestream\", methodArgs, null)" is null);
has the final quote character out of place. It should be after the "is null", right before the ");".
We also had to make sure we got the instanceName built correctly. For example, if we had "mymachine\myinstance", we had to make sure that "instanceName=myinstance" and not the full name. Further, if we had "mymachine" (the default instance), we had to have "instanceName=MSSQLSERVER". Maybe that is Greg's problem -- when we had the instanceName set to the wrong thing, we got the same results Greg reports.
I am new to PowerBuilder.
I want to retrieve the data from MSAccess tables and update it to corresponding SQL tables. I am not able to create a permanent DSN for MSAccess because I have to select different MSAccess files with same table information. I can create a permanent DSN for SQL server.
Please help me to create DSN dynamically when selecting the MSAccess file and push all the tables data to SQL using PowerBuilder.
Also give the full PowerBuilder code to complete the problem if its possible.
In Access we strongly suggest not using DSNs at all as it is one less thing for someone to have to configure and one less thing for the users to screw up. Using DSN-Less Connections You should see if PowerBuilder has a similar option.
Create the DSN manually in the ODBC administrator
Locate the entry in the registry
Export the registry syntax into a .reg file
Read and edit the .reg file dynamically in PB
Write it back to the registry using PB's RegistrySet ( key, valuename, valuetype, value )
Once you've got your DSN set up, there are many options to push data from one database to the other.
You'll need two transaction objects in PB, each pointing to its own database. Then, you could use a Data Pipeline object to manage the actual data transfer.
You want to do the DSNLess connection referenced by Tony. I show an example of doing it at PBDJ and have a code sample over at Sybase's CodeXchange.
I am using this code, try it!
//// Profile access databases accdb format
SQLCA.DBMS = "OLE DB"
SQLCA.AutoCommit = False
SQLCA.DBParm = "PROVIDER='Microsoft.ACE.OLEDB.12.0',DATASOURCE='C:\databasename.accdb',DelimitIdentifier='No',CommitOnDisconnect='No'"
Connect using SQLCA;
If SQLCA.SQLCode = 0 Then
Open ( w_rsre_frame )
else
MessageBox ("Cannot Connect to Database", SQLCA.SQLErrText )
End If
or
//// Profile access databases mdb format
transaction aTrx
long resu
string database
database = "C:\databasename.mdb"
aTrx = create transaction
aTrx.DBMS = "OLE DB"
aTrx.AutoCommit = True
aTrx.DBParm = "PROVIDER='Microsoft.Jet.OLEDB.4.0',DATASOURCE='"+database+"',PBMaxBlobSize=100000,StaticBind='No',PBNoCatalog='YES'"
connect using aTrx ;
if atrx.sqldbcode = 0 then
messagebox("","Connection success to database")
else
messagebox("Error code: "+string(atrx.sqlcode),atrx.sqlerrtext+ " DB Code Error: "+string(atrx.sqldbcode))
end if
// do stuff...
destroy atrx